1

I would like to replace the word "custom" with

<span class="persProd">custom</span>.

This is my code but not work:

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

How can i do? Thanks for any help

Jackom
  • 384
  • 3
  • 16
  • Does this answer your question? [How can i use php's preg\_replace with a simple string and wildcards?](https://stackoverflow.com/questions/7050152/how-can-i-use-phps-preg-replace-with-a-simple-string-and-wildcards) – Mech Oct 01 '20 at 17:57
  • Also [don't parse html with regex](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Wesley Smith Oct 01 '20 at 18:09

2 Answers2

2

I would do it like this. Watch out for 'custom' being in the $subject string twice. It will be replaced both times. I used spaces like so: ' 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>

Here is the str_replace() page in the php manual for more.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Christopher
  • 162
  • 4
0

This is my example and it will working not only with tags (some unique strings too).

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

?>