2

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'
2
  • You mean to say you want the string between / and . ? Commented Mar 4, 2011 at 10:22
  • See regex design tools and regular-expressions.info to learn the syntax Commented Mar 4, 2011 at 10:23

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3
$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

2 Comments

Your forgot to add delimiter to your regex.
thanks, I don't know the php regex syntax that well. Why does it require a delimiter when it's already in a string? I mean, I understand putting it between delimiters (Perl), putting it in a string (Python), but why both?
2

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);

Comments

0
$string = preg_replace('~^.*/(.*?)\..*$~',"$1",$string);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.