Justtechjobs.com Find a programming school near you






Online Campus Both


php3-list | 2000051

Re: [PHP3] ungreedy regexp's From: Alfred Perlstein (bright <email protected>)
Date: 05/01/00

* Nicholas Pappas <nick <email protected>> [000501 13:42] wrote:
> Hello again... more questions from the realm of Regular
> Expressions!
>
> Thanks to Alfred and Cynic for the previous help -- my past
> problems are working great! ... too bad I only got 2 more steps forward
> before I ran into a wall. :(
>
> My Problem:
>
> I have the following string (in psuedo html markup language):
>
> $s = "blah [url]www.link1.com[/url] blah [url]http://www.link2.com[/url]";
>
> Now, I want to replace the [url] with a <A HREF="...">, with
> what's inside the two tags, and a [/url] with a </A>. My current RegExp
> looks like this:
>
> $re = "\[url\]((http://)?(.*))\[/url\]";
>
> If I run this on a string with just 1 "url block" (ie: "blah
> [url]...[/url]") everything works great, but it is when I stick more then
> one "url block" in the mix that trouble insues.
> What comes out is that the first [url] and that very last [/url]
> tags are being match -- I understand that the regular expression is being
> greedy, but I don't understand why I can't stop it from being so.
> If I replace the above expression with:
>
> $re = "\[url\]((http://)?(.*?))\[/url\]";
>
> ... which is what the documentation claims to be "ungreedy"
> (thanks for the link Cynic), but I get the *same* output as if I didn't
> add the '?'.
>
> Can anyone see where I have gone wrong, and hopefully point me in
> the right direction?

This threw me for a bit, but basically it's because you're most likely
still using ereg() and not preg() functions.

This code works for me:

    $input = "[url]foo[/url] [url]bar[/url]";

    $string = preg_replace("/\[url\](.*?)\[\/url\]/", "&gt; \\1 &lt;", $input);
        
    echo "<html><head></head><body>$string</body></html>";

I'm not sure if ereg has ungreedy, don't have time to check.

later,

-- 
-Alfred Perlstein - [bright <email protected>|alfred <email protected>]
"I have the heart of a child; I keep it in a jar on my desk."

-- PHP 3 Mailing List <http://www.php.net/> To unsubscribe, send an empty message to php3-unsubscribe <email protected> To subscribe to the digest, e-mail: php3-digest-subscribe <email protected> To search the mailing list archive, go to: http://www.php.net/mailsearch.php3 To contact the list administrators, e-mail: php-list-admin <email protected>