PHP - 替换标签范围内的特定单词
PHP - Replace specific word inside tag span
我想用
替换单词“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;
我该怎么办?
感谢您的帮助
我会这样做。注意 'custom' 在 $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() 页面以了解更多信息。
这是我的例子,它不仅适用于标签(也适用于一些独特的字符串)。
<?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;
?>
我想用
替换单词“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;
我该怎么办? 感谢您的帮助
我会这样做。注意 'custom' 在 $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() 页面以了解更多信息。
这是我的例子,它不仅适用于标签(也适用于一些独特的字符串)。
<?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;
?>