简体   繁体   中英

Reposition value of string after replace html tag - PHP

ex1: This <b>is bold</b> and this <i>is italic</i> this is <i>also italic</i>

ex2: This is <b><i>bold-italic</i></b> But this <b>is bold</b> this is <b>also bold</b>

Now i can get position of string between tags by recursive strpos function.

But i will remove html tags, and want to get those strings re position value.

Like:

First bold string in position of 5 and 15. But when i remove tags, it wont stay on same position.

Can you please give me some idea, how to get reposition of string after strip tags?

Here is the recursive strpos found in this forum:

function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {               
    $offset = strpos($haystack, $needle, $offset);
    if($offset === false) {
        return $results;           
    } else {
        $results[] = $offset;
        return strpos_recursive($haystack, $needle, ($offset + 1), $results);
    }
}

So, i can get position of string by using this function. But how to get reposition after remove tags?

First of all, it is recommended to use a proper HTML parsing function/library to handle this. However, if you really want regex, you could use the following query to match the tags and their inner text:

<(\w+)>(.*?)<\/\1>

And you could replace it with the inner group, marked as \2 . So it would look something like this:

preg_replace("<(\w+)>(.*?)<\/\\1>", "\\2", str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM