views:

228

answers:

4

Hi,

Is there anyway to skip the first match when using regex and php.

Or is there some way of achieveing this using str_replace.

Thanks

UPDATE I am trying to remove all the instances of a string from another string but I want to retain the first occurance e.g

$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';

Ouput string would be:

This is a test string to test to removing the word test

A: 

assume 'blah' is your regex pattern, blah(blah) will match and capture the second one

Charles Ma
+1  A: 

Easy PHP way:

<?php
    $pattern = "/an/i";
    $text = "banANA";
    preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
    preg_match($pattern, $text, $matches, 0, $matches[0][1]);
    echo $matches[0];
?>

will give you "AN".

UPDATE: Didn't know it was a replace. Try this:

<?php
    $toRemove = 'test';
    $string = 'This is a test string to test to removing the word test';
    preg_match("/$toRemove/", $string, $matches, PREG_OFFSET_CAPTURE);
    $newString = preg_replace("/$toRemove/", "", $string);
    $newString = substr_replace($newString, $matches[0][0], $matches[0][1], 0);
    echo $newString;
?>

Find the first match and remember where it was, then delete everything, then put whatever was in the first spot back in.

Amadan
Works perfectly, thanks
scott
Eh, thought of a cleverer way. <?php $toRemove = 'test'; $string = 'This is a test string to test to removing the word test'; $found = 0; echo preg_replace("/($toRemove)/e", '$found++ ? \'\' : \'$1\'', $string); ?>
Amadan
@Amadan - Thanks.Just so I understand it, the following: `$found++ ? \'\' : \'$1\'`follows this pattern:`if($found == 0)````{```` replace with the first result found````}````else````{```` replace with empty string````}`
scott
That's exactly right.
Amadan
A: 

Why don't you catch ever matches (using preg_match()) into an array, and after that you have nothing more to do, than count from the second (array1) one

Nort
A: 
preg_replace('/((?:^.*?\btest\b)?.*?)\btest\b/', '$1', $string);

The idea is to match and capture whatever precedes each match, and plug it back in. (?:^.*?test)? causes the first instance of test to be included in the capture. (All the \bs are to avoid partial-word matches, like the test in smartest or testify.)

Alan Moore