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! :)