-1

I'm trying to extract id from a url, below my code:

$text = '/news/35555555555-title-of-the-article';
$text = eregi("news/(.*)-",$text,$regs); 
echo $regs[1];

I want to echo only

35555555555

but above code is printing:

35555555555-title-of-the
AlbaStar
  • 469
  • 5
  • 12

2 Answers2

2

You have to use a character class that excludes the hyphen instead of the dot that matches any character. ereg* functions use the POSIX syntax and don't have non-greedy quantifiers:

$text = '/news/35555555555-title-of-the-article';
$text = eregi("news/([^-]*)-",$text,$regs); 
echo $regs[1];

Note that ereg* functions are deprecated since php 5.3 and produce a warning until the 5.6 versions included. They have been removed since php 7.0 and produce a fatal error. However, mb_ereg* functions are always available. Note also that php 5.2 is no more supported since Jan 2011 (in other words, you have to upgrade your php version).

Instead, use the preg_* functions that use the backtracking engine with a Perl-like syntax (with non-greedy quantifiers in particular):

$text = '/news/35555555555-title-of-the-article';
preg_match('~/news/(.*?)-~', $text, $m);
echo $m[1];

Without regex, you can use a formatted string:

$text = '/news/35555555555-title-of-the-article';
list ($id) = sscanf(strtolower($text), '/news/%[^-]-');
echo $id;

or more common string functions:

$text = '/news/035555555555-title-of-the-article';
list($id,) = explode('-', substr(strrchr($text, '/'), 1)); 
echo $id;
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

The dirty but easy way is

$text = '/news/35555555555-title-of-the-article';
$parts = end(explode('/', $text));
$param = explode('-', $parts);
echo $param[0];
Ashik Basheer
  • 1,531
  • 3
  • 16
  • 36