Ereg() function not working

Is there something wrong with my regular expression? I cannot get this line of code to work:

ereg(“^C:.*.gif$”, $string, $regs);

It is supposed to find all image locations in a string (consisting of gif file locations), starting with c: and any character, then at the end .gif

(It should then store them in an array $regs)

Please note that ereg has been deprecated in PHP 5 and removed since PHP 7.

You might want to use preg_match_all instead here:

preg_match_all('~^c:.*\.gif$~i`, $string, $regs);

I’ve added the i modifier at the end to make it case insensitive. That way it will also match C:\blah\blah.GIF for example.

Thanks a bunch! That explains everything, and thanks for the addition of the i!

Careful here.

You need to make that match-all non-greedy, or you’re going to consume the entire string for a single match. (Also… if by definition it’s a string with multiple matches, you’re not going to be able to ^ and $… is this a multiline string?)

You are absolutely correct!

It should be like this:

preg_match_all('~\bc:[^\s]+?\.gif\b~i', $string, $regs);

\b is for a word boundary. So the first is one is either for the start of the whole string, or a space, while the second one is for the end of the string, or a space.

I’ve also changed .* to [^\s]+? to only match anything that isn’t a space. Otherwise it would combine files if one of them wasn’t a GIF.

Well for starters, try using the new pattern rpkamp’s given you.
You can also somewhat simplify your code with a foreach. It’ll help you avoid the other problem you’ve got - putting array markers inside a string doesnt work without help.

If you want to stick with the for loop, and keep the variable inside the string, you’ll need to add some curly braces so the string knows where the variable reference ends, and the string begins again.

It’s been a while since I did complex string insertion, but i believe it would have to be

echo "<img src='{$regs[$a]}' /><br>";

I usually go straight for printf or sprintf in those cases:

printf('<img src="%s" /><br>', $regs[$a]);

Where %s will be replaced by whatever is in $regs[$a].

Thanks!

Thanks for the help!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.