1

I am trying to replace text between two tags in a html document. I want to replace any text that isn't enclosed with a < and >. I want to use str_replace to do this.

php $string = '<html><h1> some text i want to replace</h1><p>some stuff i want to replace </p>';

$text_to_echo = str_replace("Bla","Da",$String);
echo $text_to_echo;
4
  • I guess you need Regex to achieve this. Commented Nov 13, 2013 at 18:55
  • 1
    html is best handled by parsing it as XML. Some things can be achieved with regular expressions, but str_replace is not suitable for the task at all. Commented Nov 13, 2013 at 18:57
  • Obligatory link to "RegEx match open tags except XHTML self-contained tags" thread: stackoverflow.com/questions/1732348/… Commented Nov 13, 2013 at 19:01
  • 1
    I would suggest you read this SO question stackoverflow.com/questions/8687778/… Commented Nov 13, 2013 at 19:01

2 Answers 2

1

Try this:

    <?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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, would there be a way to do this word by word. For example replace "text" with "hello" and "want" with "cake"
Hi. Would there be a easy way to implement MySQL with this as i want to fetch the arrays from a DB instead of having to manually insert them.
Hi, if you have in plan further to use these data, which were inserted in mysql, instead of replacing, then worth doing this one time.
0

str_replace() can not handle this

You will need regex or preg_replace for that

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.