PHP preg_replace regular expression
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 man开发者_开发技巧y 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'
Thanks in advance!
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.
$s = preg_replace("#^.*/(.*?)\\..*$#","$1",$string)
Explanation:
^ matches start of string
.* matches a string of arbitrary characters (greedy)
/ matches the /
(.*?) matches a string of arbirtrary characters (non-greedy)
\. matches a dot
.* matches a string of arbitrary characters
$ matches end of string
You don't need regex for this case, it would be over kill. You can just use the build in substr and strpos functions.
$from = strpos($string, '/') + 1;
$to = strpos($string, '.');
echo substr($string, $from, $to - $from);
// echos 03b
Ofcause you can do this in one line, the above was just for clarity
echo substr($string, strpos($string, '/') + 1, strpos($string, '.') - strpos($string, '/') - 1);
$string = preg_replace('~^.*/(.*?)\..*$~',"$1",$string);
精彩评论