简体   繁体   中英

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';

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM