1

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!

youmotherhaveapples
  • 347
  • 2
  • 3
  • 10
  • 1
    *"But isn't working."*. You need to enable error logging, follow the error log, start to learn about the messages presented to you. – hakre Aug 30 '13 at 05:49
  • possible duplicate of [How to get useful error messages in PHP?](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php) – hakre Aug 30 '13 at 05:49
  • Like `$after = '\/';` – Bora Aug 30 '13 at 05:50

2 Answers2

3

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.

Paul
  • 139,544
  • 27
  • 275
  • 264
0

Have you tried escaping the /? Instead of

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

try

$first = 'aaa\/';
$after = '\/';
Vince
  • 1,517
  • 2
  • 18
  • 43