How to do Search & Replace using Preg_match with PHP

Lets say you want a search and replace statement in PHP that can find either:

The score was: 18 to 27 New York over Miami in the end.

or:

The score was: 07 to 21 Cleveland over Pittsburgh in the end.

As you can see in the two example strings, the both start with:

The score was:

and end with:

in the end.

So those are the constants and nearly anything could be in between the start and end text so we need way to search and replace with some sort of regular expression using PHP. Here is what I found:

$string =”The score was: 07 to 21 Cleveland over Pittsburgh in the end.”;
$pattern = ‘/The score was:.*in the end./’;
$replacement = ‘Whatever you want in place of string goes here’;
echo preg_replace($pattern, $replacement, $string);
echo $string;

The above could be used to replace a dynamic string with a constant string or even just find and delete a sting that’s not always the same by changing replacement to “”. By using two quotes you say replace the string with nothing. Generally in the pattern variable above, we are using the “.*” or dot start, to say “anything can go here”, but the search string contains what is before and after dot start. This is a useful expression to use so I thought I’d post it. Good luck.

 

Leave a Reply

Your email address will not be published. Required fields are marked *