Search code examples
phpregexpreg-replacetext-extractiontext-parsing

Get string between two specific characters in a string


How to remove anything before a given character and anything after a given character with preg_replace using a regular expression? Of course this could be done in many other ways like explode and striping the string. But I am curious about preg_replace and regex.

So the only thing I need from the string below is 03b and remove every thing before/and slash (/) and after/and dot (.)

$string = 'rmbefore/03b.rmafter'

Solution

  • You can use backreferences in preg_replace to do this:

    preg_replace('#.*/([^\.]+)\..*#', '$1', $input);
    

    This searches for anything up to a slash, then as much of the following string that is not a dot, put this in group 1 (thats the '()' around it), followed by a dot and something else and replaces it with the contents of group 1 (which is the expression within parentheses and should be "03b" in your example). Here is a good website about regex: http://www.regular-expressions.info/php.html.

    Hope this helps.