Я пытаюсь заменить текст между двумя тегами в html-документе. Я хочу заменить любой текст, который не заключен в <и>. Я хочу использовать str_replace для этого.
php $string = '<html><h1> some text я want to replace</h1><p>some stuff я want to replace </p>';
$text_to_echo = str_replace("Bla","Da",$String);
echo $text_to_echo;
Попробуй это:
<?php
$string = '<html><h1> some text i want to replace</h1><p>
some stuff i want to replace </p>';
$text_to_echo = preg_replace_callback(
"/(<([^.]+)>)([^<]+)(<\\/\\2>)/s",
function($matches){
/*
* Indexes of array:
* 0 - full tag
* 1 - open tag, for example <h1>
* 2 - tag name h1
* 3 - content
* 4 - closing tag
*/
// print_r($matches);
$text = str_replace(
array("text", "want"),
array('TEXT', 'need'),
$matches[3]
);
return $matches[1].$text.$matches[4];
},
$string
);
echo $text_to_echo;
str_replace()
не может справиться с этим
Вам понадобится regex
или preg_replace
для этого
Regex
для достижения этой цели.