MiLaD TNT MiLaD TNT - 4 months ago 10
PHP Question

How can I replace a substring with a link?

I have a string in text from position 6 to 11 and I want to replace it with an HTML link

How can I do it?

$text = 'hello world this is my question , plz help';
$position_from = 15;
$position_to = 20;
$link = 'http://google.com';


I need a function that gives me this:

$text = 'hello <a href="http://google.com">world</a> this is my question , plz help';

Answer

To replace a substring with a modified version of the same substring, first calculate the length of the substring to be replaced, by subtracting the start position from the end position.

$len = $to - $from;

Then you can make the replacement using substr and substr_replace:

$link = '<a href="http://google.com">' . substr($text, $from, $len) . '</a>';
$text = substr_replace($text, $link, $from, $len);

or replace using a regular expression with preg_replace.

$pattern = "/(?<=^.{{$from}})(.{{$len}})/";
$text = preg_replace($pattern, '<a href="http://www.google.com">$1</a>', $text);

For multi-byte safe operation, since there is not mb_substr_replace, you can just use mb_substr repeatedly:

$text = mb_substr($text, 0, $from)
        . "<a href='$url'>" . mb_substr($text, $from, $len) . '</a>'
        . mb_substr($text, $to);
Comments