faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

How can I replace a single reg exp match using ereg_replace?

Aug 4th, 1999 07:51
Nathan Wallace, Steve Edberg


Well, I think you can do that via PHP's Perl-compatible regex support
(since PHP 3.0.10, I think), but I haven't used that yet, so here's one
way to do it using PHP's standard POSIX regex support:

    $RegEx = '-+';  # An example regex, that matches 1 or more dashes
    $ReplacementString = '-dashes-'; # what to replace the match with

    # Here's the meat of the procedure; the third param in split() is 
    # the maximum of elements that the string will be split into. Using 
    # 2 will split on the first occurence and ignore subsequent matches.

    $Parts = split($RegEx, $String, 2);
    $NewString = $Parts[0].$ReplacementString.$Parts[1];