25

Possible Duplicate:
Converting ereg expressions to preg

<?php
$searchtag = "google";
$link = "http://images.google.com/images?hl=de&q=$searchtag&btnG=Bilder-Suche&gbv=1";
$code = file_get_contents($link,'r');
ereg("imgurl=http://www.[A-Za-z0-9-]*.[A-Za-z]*[^.]*.[A-Za-z]*", $code, $img);
ereg("http://(.*)", $img[0], $img_pic);
echo '<img src="'.$img_pic[0].'" width="70" height="70">'; ?> 

And i get this error

Deprecated: Function ereg() is deprecated in C:\Program Files\EasyPHP-5.3.8.1\www\m\img.php on line 5

Deprecated: Function ereg() is deprecated in C:\Program Files\EasyPHP-5.3.8.1\www\m\img.php on line 6

preg_match() functions give this error

Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in C:\Program Files\EasyPHP-5.3.8.1\www\m\img.php on line 6

Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in C:\Program Files\EasyPHP-5.3.8.1\www\m\img.php on line 7

Community
  • 1
  • 1
robpal
  • 846
  • 4
  • 10
  • 21

2 Answers2

47
  1. ereg is deprecated. Don't use it.
  2. The preg functions are all "Perl regular expressions" meaning you need to have some sort of beginning and end marker on your regex. Often this will be / or #, but any non alpha-numeric will do fine.

For example, these will work:

preg_match("/foo/u",$needle,$haystack);
preg_match("#foo#i",$needle,$haystack);
preg_match("@foo@",$needle,$haystack);
preg_match("\$foo\$w",$needle,$haystack); // bad idea because `$` means something
                                          // in regex but it is valid anyway
                                          // also, they need to be escaped since
                                          // I'm using " instead of '

But this will not:

preg_match("foo",$needle,$haystack); // no delimiter!
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • 1
    When I try preg_match("/foo/g",$needle,$haystack); It doesn't work. I got a PHP warning, Unknown modifier 'g' – James Mar 23 '14 at 04:03
  • As per [this answer](http://stackoverflow.com/a/3578703/1676444) on another question, `/g` pattern modifier will not work in PHP. You would need to use `preg_match_all` instead in your example. [List of Pattern Modifiers for PHP](http://php.net/manual/en/reference.pcre.pattern.modifiers.php) – Turnerj Jan 25 '15 at 07:22
3

With preg_match() your regex must begin and end with a delimiter such as / with few exceptions (for example adding "i" at the end for case-insensative).

e.g.

preg_match('/[regex]/i', $string)
Yes Barry
  • 9,514
  • 5
  • 50
  • 69
  • "A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character." [Manual](http://www.php.net/manual/en/regexp.reference.delimiters.php). But yes, you're right, the delimiters are missing. – lonesomeday Nov 16 '11 at 22:29