Jump to content

Help with ereg_replace


isopogon

Recommended Posts

I'm trying to use ereg_replace to turn a string like:
[code]http://www.server.com/link.html[This is a Caption][/code]
into a string like:
[code]<a href="http://www.server.com/link.html">This is a Caption</a>[/code]

I started with:
[code]// match protocol://address/path/
$temp = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">\\0</a>", $temp);
// match www.something
$temp = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)([a-zA-Z0-9])", "\\1<a href=\"http://\\2\">\\3</a>", $temp);[/code]

But can't figure out how to modify these to produce the result I want.
Link to comment
https://forums.phpfreaks.com/topic/27734-help-with-ereg_replace/
Share on other sites

Thanks.
What works beautifully :), but I realised I didn't ask my original question properly.
The caption in the square brackets doesn't always exist.  Sometimes it's just a plain URL.  In this case, the URL will be the caption.

How do I specify that second substring is optional, and to use the first substring for the caption if the second one doesn't exist?

Examples:
[code]http://server.com/file.html[Caption]
http://anotherserver.com/file2.html

... should produce...

<a href="http://server.com/file.html">Caption</a>
<a href="http://anotherserver.com/file2.html">http://anotherserver.com/file2.html</a>
[/code]

Thanks again.
Make a call-back function and check if the caption was matched, if not, return the url as the caption.

ex:
[code=php:0]<?php

function link_it($url, $desc) {

// Use the URL if no caption was matched...
if (!$desc) {

$link = "<a href=\"$url\">$url</a>";

} else {

$link = "<a href=\"$url\">$desc</a>";

}

return $link;

}


$string = 'bla bla bla http://www.server.com/link.html[This is a Caption] bla bla bla';

echo preg_replace('/(http:\/\/[^\s\[]+)(\[(.*?)])?/eis', 'link_it("\\1", "\\3")', $string);

?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.