簡體   English   中英

如何用鏈接替換子字符串?

[英]How can I replace a substring with a link?

我在第6到第11位的文本中有一個字符串,我想用HTML鏈接替換它

我該怎么做?

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

我需要一個函數給我這個:

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

要使用相同子字符串的修改版本替換子字符串,首先通過從結束位置減去起始位置來計算要替換的子字符串的長度。

$len = $to - $from;

然后你可以使用substrsubstr_replace進行替換:

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

或使用帶有preg_replace的正則表達式替換。

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

對於多字節安全操作,由於沒有mb_substr_replace ,您可以重復使用mb_substr

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM