Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.)

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

Late answer but it might be usefull to people.

$string = "This is a test string to test something with the word test and replacing test";
$replace = "test";
$tmp = explode($replace, $string);
$tmp[0] .= $replace;
$newString = implode('', $tmp);
echo $newString; // Output: This is a test string to something with the word and replacing 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top