Instead of working with preg_replace
, use substr_replace
to do your string replacement and strpos to find the start and end points within the string based on the parameters you pass. Your pattern is a simple string, so it doesn't require a regular expression, and substr_replace will allow you to specify a start and end point within the string to do replacements (which seems to be what you're looking for).
EDIT:
Based on your comment, it sounds like you have to do a lot of checking. I haven't tested this, so it may have a bug or two, but try a function like this:
function replace($number, $pattern, $replacement)
{
$input = "The quick sample_text_1 56 quick sample_text_2 78 fox jumped over the lazy dog.";
$end_pos = strpos($input, $number);
$output = "";
if($end_pos !== false && substr_count($input, $pattern, 0, $end_pos))
{
$start_pos = strrpos(substr($input, 0, $end_pos), $pattern);
$output = substr_replace($input, $replacement, $start_pos, ($start_pos + strlen($pattern)));
}
return $output;
}
This function does the following:
- First, check that the "number" parameter even exists in the string (
$end_pos !== false
)
- Check that your pattern exists at least once in between teh beginning of the string and the position of the number (
substr_count($input, $pattern, 0, $end_pos)
)
- Use
strrpos
function to get the position of the last occurrence of the pattern within the substring
- Use the start position and the length of the pattern to insert your replacement string using
substr_replace