【问题标题】:PHP - Replace specific word inside tag spanPHP - 替换标签范围内的特定单词
【发布时间】:2020-10-01 17:54:47
【问题描述】:
我想将单词“custom”替换为
<span class="persProd">custom</span>.
这是我的代码,但不起作用:
$output = '<a href="www.mysite.com/custom-products"><span>Special custom products</span></a>';
$test = '~<span>custom</span>~';
$outputEdit = preg_replace($test, '<span class="persProd">custom</span>', $output);
echo $outputEdit;
我该怎么办?
感谢您的帮助
【问题讨论】:
标签:
php
replace
tags
preg-replace
word
【解决方案1】:
我会这样做。注意 $subject 字符串中的“custom”两次。它将被替换两次。我使用了这样的空格:'自定义'
$subject = '<a href="www.mysite.com/custom-products"><span>Special custom products</span></a>';
$search = ' custom ';
$replace = '<span class="persProd"> custom </span>';
$outputEdit = str_replace($search, $replace, $subject);
echo $outputEdit;
Output: <span>Special<span class="persProd"> custom </span>products</span>
这里是 php 手册中的str_replace() 页面了解更多信息。
【解决方案2】:
这是我的示例,它不仅适用于标签(也适用于一些独特的字符串)。
<?php
function string_between_two_tags($str, $starting_tag, $ending_tag, $string4replace)
{
$start = strpos($str, $starting_tag)+strlen($starting_tag);
$end = strpos($str, $ending_tag);
return substr($str, 0, $start).$string4replace.substr($str, $end);
}
$output = '<a href="www.mysite.com/custom-products"><span>Special custom products</span></a>';
$res = string_between_two_tags($output, '<span>', '</span>', 'custom');
echo $res;
?>