youmotherhaveapples
youmotherhaveapples

Reputation: 387

/ (slash) in preg_match

I have this section some/aaa/9321/something from which I want to extract only 9321. "something" always differs, "aaa" is alyways static. So, I used:

$text = "something/aaa/9321/something";
$first = 'aaa/';
$after = '/';
preg_match("/$first(.*)$after/s",$text,$result);
echo $result;

But isn't working. Can somebody please tell me what I need to use? I've tried this too:

$text = "something/aaa/9321/something";
$first = 'aaa';
preg_match("|$first(.*)|",$text,$result);
echo substr($result['1'], 1, 4);

But between aaa and something not always 4 characters.

Sorry for bad english. Thanks!

Upvotes: 1

Views: 2517

Answers (2)

Paul
Paul

Reputation: 141877

You should always preg_quote strings when you want them to be taken literally in a regular expression:

$text = 'something/aaa/9321/something';
$first = preg_quote('aaa/', '/');
$after = preg_quote('/', '/');
preg_match("/$first(.*)$after/s",$text,$result);
echo $result[1]; // '9321'

Demo

The problem was caused by the fact that / is the delimiter in your regex. You could have also solved this problem by using a different delimiter, such as ~, however, you would just run into the same problem as soon as your string had a ~ or any other character with a special meaning like ., or ?. By using preg_quote, you won't run into this problem again.

Upvotes: 3

Vince
Vince

Reputation: 1527

Have you tried escaping the /? Instead of

$first = 'aaa/';
$after = '/';

try

$first = 'aaa\/';
$after = '\/';

Upvotes: 0

Related Questions