如果包含特定字符串,则删除 link
Remove link if contains specific string
我有这个 PHP 代码,在发送电子邮件之前将特定单词转换为 link。
$message = str_replace(
'hello',
'<a id="get-ahead-link" style="color: #ffa503;" href="https://somelink.com"> hello </a>',
$message,
$count);
上面的代码完全可以工作,但是当 link 和单词 'hello' 已经包含时我遇到了问题。
示例:
hello world. Please visit my site: http://helloworld.com.
这变成:
但我需要的是:
hello world. Please visit my site: http://helloworld.com.
这可能吗?我的工作缺少什么?
您可以使用 preg_replace
(replacement using regular expressions) and surround your string with (?<=^|\s)
("is either at the beginning of the string or preceded by a space character") and \b
(word boundaries):
$message = preg_replace(
'/(?<=^|\s)hello\b/',
'<a id="get-ahead-link" style="color: #ffa503;" href="https://somelink.com">hello</a>',
$message,
-1,
$count
);
注意:我留下了额外的参数来检索 $count
。
其他(无关)注意事项:在大多数情况下应避免使用此类内联 HTML 样式。
我有这个 PHP 代码,在发送电子邮件之前将特定单词转换为 link。
$message = str_replace(
'hello',
'<a id="get-ahead-link" style="color: #ffa503;" href="https://somelink.com"> hello </a>',
$message,
$count);
上面的代码完全可以工作,但是当 link 和单词 'hello' 已经包含时我遇到了问题。
示例:
hello world. Please visit my site: http://helloworld.com.
这变成:
但我需要的是:
hello world. Please visit my site: http://helloworld.com.
这可能吗?我的工作缺少什么?
您可以使用 preg_replace
(replacement using regular expressions) and surround your string with (?<=^|\s)
("is either at the beginning of the string or preceded by a space character") and \b
(word boundaries):
$message = preg_replace(
'/(?<=^|\s)hello\b/',
'<a id="get-ahead-link" style="color: #ffa503;" href="https://somelink.com">hello</a>',
$message,
-1,
$count
);
注意:我留下了额外的参数来检索 $count
。
其他(无关)注意事项:在大多数情况下应避免使用此类内联 HTML 样式。