PHP- How do I do this? (Regex)

Bes

Bes

Soldato
Joined
18 Oct 2002
Posts
7,318
Location
Melbourne
Hi

In perl, I can write: (Syntax may not be 100% but you get the idea)

my $var=foobarbar;
$var=~m/foo(.*)ar^/;
print $0;

and get barb as the result. (Because I match the contents of var)

If i try and replicate this in PHP, it does not work (It seems to trip up because you cannot write things like $1 on new lines)

Is this really the case? How can I get around this?

Thanks
 
Last edited:
$var = 'foobarbar';
if(eregi("^foo(.*)ar$", $var, $m))
print $m[1];

the $m is passed in by reference, so retains its value once the eregi() func has returned
 
And now that i've hurredly typed that and gotten the first reply in, I'll expand ever so slightly: that $m becomes an array and contains entries for every set of parentheses matched, so $m[1] the first set, $m[2] the second set etc etc, and $m[0] the entire string which was matched
 
Thanks guys :) I did it a totally different way in the end:

PHP:
$filename=filter_var(substr(strrchr($_SERVER["REQUEST_URI"], '/'), 1), FILTER_SANITIZE_STRING);
$querySeoName= substr($filename, 0, strpos ($filename, '.'));
Just a question.... $querySeoName (which starts life as $filename, which is part of the URL the user has entered/ been lined to) exists because I am splicing my own workflow into a cart with SEO optimisation, and in order to keep the two apps (My app and the cart) as seperate as possible to make upgrades less painful, I am using the last part of the URL ($queryseoname) to do a lookup in the cart's DB where it keeps a record of the SEO freindly names and corresponding product ID as I do not want to merge the two products together really. (My app and the cart share common product IDs). Now, obviously I need to stop people from being able to put naughty code in the URL bar which could lead to a hack... will (SANATIZE_STRING) be sufficient?

Thanks
 
Last edited:
RegEx makes my eyes bleed at the best of times but preg match is helpful for what you are after.

Got to say, its a lot easier in Perl :)
 
Back
Top Bottom