MiLaD TNT MiLaD TNT - 4 years ago 123
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 = '';

I need a function that gives me this:

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

Answer Source

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="">' . 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="">$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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download