PDA

View Full Version : Replace in a string


12-17-2000, 04:39 AM
Is it possible, and if so, how, to search for two unique specific text patterns in a string, and replace both the two patterns and everything in between them with another text pattern?

Specifically, suppose a string contains this text:
This is a test message with a [URL=http://www.somesite.com]hyperlink[/ URL] sample.[/quote]

And I would like to replace everything between the URL tags, including the URL tags, with some other text (like maybe "(hyperlink)", including the parentheses).

Note that the function would have to search for both formats of the URL opening code, the simple one and the named one. In other words, both
[code][URL] and [URL=would need to be searched for.

12-17-2000, 07:44 AM
This is easy with a regex:

// do xxx
$text=eregi_replace("\\[url\\]www.([^\\[]*)\\[/url\\]","<a href=\"http://www.\\1\" target=_blank>(hyperlink)</a>",$text);
$text=eregi_replace("\\[url\\]([^\\[]*)\\[/url\\]","<a href=\"\\1\" target=_blank>(hyperlink)</a>",$text);

// do yyy (xxx)
$text=eregi_replace("\\[url=\"([^\"]*)\"\\]([^\\[]*)\\[\\/url\\]","<a href=\"\\1\" target=_blank>(hyperlink)</a>",$text);
$text=eregi_replace("\\[url=([^\"]*)\\]([^\\[]*)\\[\\/url\\]","<a href=\"\\1\" target=_blank>(hyperlink)</a>",$text);


(almost) Straight from the vB source :)


[Edited by Menno on 12-17-2000 at 05:22 AM]