Simple: How to replace “all between” with php?

2019-01-27 13:15发布

问题:

$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>

So what code am i looking for?

回答1:

$search = "/[^<tag>](.*)[^<\/tag>]/";
$replace = "your new inner text";
$string = "<tag>i dont know what is here</tag>";
echo preg_replace($search,$replace,$string);

outputs:

<tag>your new inner text</tag>


回答2:

A generic function:

function replace_between($str, $needle_start, $needle_end, $replacement) {
    $pos = strpos($str, $needle_start);
    $start = $pos === false ? 0 : $pos + strlen($needle_start);

    $pos = strpos($str, $needle_end, $start);
    $end = $pos === false ? strlen($str) : $pos;

    return substr_replace($str, $replacement, $start, $end - $start);
}

DEMO



回答3:

$string = "<tag>i dont know what is here</tag>"

$string = preg_replace('#(<tag.*?>).*?(</tag>)#', '$1$2', $string)


回答4:

$string = "<tag>i dont know what is here</tag>"
$string = "<tag></tag>";
echo $string; // <tag></tag>

or just?

$string = str_replace($string, "<tag></tag>", $string);

Sorry, could not resist. Maybe you update your question with a few more details. ;)



回答5:

If "tag" changes:

$string = "<tag>i dont know what is here</tag>";
$string = preg_replace('|^<([a-z]*).*|', '<$1></$1>', $string)
echo $string; // <tag></tag>


回答6:

If you need to replace the portion too then this function is helpful:

$var = "Nate";

$body = "Hey there {firstName} have you already completed your purchase?";

$newBody = replaceVariable($body,"{","}",$var);

echo $newBody;

function replaceVariable($body,$needleStart,$needleEnd,$replacement){
  $start = strpos($body,$needleStart);
  $end = strpos($body,$needleEnd);
  return substr_replace($body,$replacement,$start,$end-$start+1);
}

I had to replace a variable put into a textarea that was submitted. So I replaced firstName with Nate (including the curly braces).



回答7:

If you don't know what's inside the <tag> tag, it's possible there is another <tag> tag in there e.g.

<tag>something<tag>something else</tag></tag>

And so a generic string replace function won't do the job.

A more robust solution is to treat the string as XML and manipulate it with DOMDocument. Admittedly this only works if the string is valid as XML, but I still think it's a better solution than a string replace.

$string = "<tag>i don't know what is here</tag>";
$replacement = "replacement";

$doc = new DOMDocument();
$doc->loadXML($str1);
$node = $doc->getElementsByTagName('tag')->item(0);
$newNode = $doc->createElement("tag", $replacement); 
$node->parentNode->replaceChild($newNode, $node);
echo $str1 = $doc->saveHTML($node); //output: <tag>replacement</tag>