PHP: How to Remove or Replace Strings from the Front and End of a Value CodeUnit 02 JUL 2010

Today’s little PHP hint is a pretty simple one, but one worth tackling if you are looking for a quick and easy way to strip a particular string pattern off the front and end of a value.

What we will make use of is of course PHP’s built in preg_replace functionality, basically one of the wrapper functions that brings regular expression manipulation to PHP.

Now to start off, we need to specify the string pattern we wish to search for off the front of our value. To do this we make use of the ^ regex control character that denotes the search to begin from the start of a string. To locate a string pattern off the end of our value, we make use of the $ regex control character which likewise, tells the search to commence at the back of the given string value.

We then place our two patterns in a search array, before moving on to define our replace array. Now at this stage you can choose: if you want to simply strip these patterns off the value, then simply match the search patterns with the same amount of blank string values, otherwise insert the string values you wish to replace the patterns with.

Finally, we call the preg_replace function, feeding it our search and replace arrays, as well as the input value it is to work on.

In other words, we would have something like this:

$search = array ( "/^stringatstart /","/ stringatend$/");
$replace = array ('','');

echo preg_replace($search, $replace, "stringatstart Hello World! stringatend");

And there you go, a nice and simple way to strip off specific values at either end of a string! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Guest

    Nice – just what I was looking for! If you could just expand it a bit to include wildcards and recursive replacements would be awesome!