简体   繁体   English

替换 html 标签后字符串的重新定位值 - PHP

[英]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.现在我可以通过递归strpos function 获得标签之间的字符串 position。

But i will remove html tags, and want to get those strings re position value.但我将删除 html 标签,并希望获得这些字符串的 position 值。

Like:像:

First bold string in position of 5 and 15. But when i remove tags, it wont stay on same position. 5 和 15 的 position 中的第一个bold字符串。但是当我删除标签时,它不会保留在相同的 position 上。

Can you please give me some idea, how to get reposition of string after strip tags?你能给我一些想法吗,如何在 strip 标签后重新定位字符串?

Here is the recursive strpos found in this forum:这是在该论坛中找到的递归 strpos:

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?所以,我可以通过使用这个 function 得到 position 的字符串。但是如何在删除标签后重新定位?

First of all, it is recommended to use a proper HTML parsing function/library to handle this.首先,建议使用合适的 HTML 解析函数/库来处理这个问题。 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 .您可以将其替换为标记为\2的内部组。 So it would look something like this:所以它看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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