如何从字符串中的一行中删除特定的html标签?

时间:2013-09-26 10:04:53

标签: php replace

$find = '{<p>something</p>}';
$str1 = "<p>{<p>something</p>}</p>\r\ntext<p>something else</p>";
// or
$str2 = "<p>something</p>\r\n{<p>something</p>}aa<p>t</p>\r\ntext<p>something else</p>";

基本上,$ find可以在字符串中的任何位置。新行分隔符为“\ r \ n”。

我需要在$ str中找到$ find并删除该特定字符串行中$ find周围的特定html标记。不应该从$ find中删除任何标签。

预期输出

// For $str1
$str1 = "{<p>something</p>}\r\ntext<p>something else</p>";
// For $str2
$str2 = "<p>something</p>\r\n{<p>something</p>}aat\r\ntext<p>something else</p>";

字符串可能很长,请不要使用正则表达式解决方案。

我发现了什么:

$pos = strpos($str, $find);
if ($pos !== false) {
    $contentLength = strlen($str);
    $lineStart = (int)strrpos($str, "\r\n", -$contentLength+$pos); // cast false to 0 (start of string)
    $lineEnd = strpos($str, "\r\n", $pos);
    if ($lineEnd === false)
        $lineEnd = strlen($str);

    $lineLength = $lineEnd-$lineStart;
    if ($lineLength < 0)
        return;

    var_dump(substr($str, $lineStart, $lineLength));
}

在字符串中转储该特定行。

1 个答案:

答案 0 :(得分:0)

我的最终解决方案:

function replace($find, $str, $replace) {
    $pos = strpos($str, $find);
    if ($pos !== false) {
        $delim = "\r\n";
        $contentLength = strlen($str);

        $lineStart = strrpos($str, $delim, -$contentLength+$pos);
        if ($lineStart === false)
            $lineStart = 0;
        else
            $lineStart += strlen($delim);

        $lineEnd = strpos($str, $delim, $pos);
        if ($lineEnd === false)
            $lineEnd = strlen($str);

        $lineLength = $lineEnd - $lineStart;    

        $line = substr($str, $lineStart, $lineLength);
        $posLine = strpos($line, $find); // Where $find starts
        $findLength = strlen($find);

        $line = substr_replace($line, '', $posLine, $findLength); // Remove $find from $line
        $begin = replaceTags(substr($line, 0, $posLine));
        $end = replaceTags(substr($line, $posLine));

        return substr_replace($str, $begin.$replace.$end, $lineStart, $lineLength);
    }
}
function replaceTags($str) {
    return str_replace(array('<p>', '</p>'), '', $str);
}
echo replace($find, $str, $replace);
相关问题