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
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.
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.