PHP:从字符串中删除某些字符,不包括/忽略URL


PHP: Remove certain character from string excluding/ignoring URL

我有一个字符串如下

字符串

<span class="post-excerpt"> - <a href="./posts/the-post-title">17 posts</a> - Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunc</span>

现在我想从字符串中删除-(而不是从字符串中的URL)

我曾尝试使用str_replace(),但它是从URL也删除,导致断裂的链接,当然。

任何人都可以帮我从字符串中删除-,但不是从URL

假设字符串将始终采用该格式,您可以将str_replace更改为更具体,从而忽略url中的-:

$newString = str_replace('> - <', '><', $oldString);

就像我说的,确保格式总是相同的,即> - <

您可以使用DOMDocument,它将解析HTML。这意味着您只能对元素的内容使用str_replace,而不必冒险修改它们的属性。

它看起来更冗长,但它也更安全,如果你的HTML格式在将来有轻微的变化,它仍然会继续工作:

$html = '<span class="post-excerpt"> - <a href="./posts/the-post-title">17 posts</a> - Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunc</span>';
$doc = new DOMDocument();
$doc->loadHTML($html);
// DOMDocument creates a valid HTML document, adding a doctype, <html> and <body> tags
// The following two lines remove them
// http://stackoverflow.com/a/6953808/2088135
$doc->removeChild($doc->firstChild);
$doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild);
$span = $doc->getElementsByTagName('span')->item(0);    
foreach ($span->childNodes as $node) {
    $node->nodeValue = str_replace(' - ', '', $node->nodeValue);
}
echo $doc->saveHTML();
输出:

<span class="post-excerpt"><a href="./posts/the-post-title">17 posts</a>Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunc</span>

不优雅,但工作和通用的方法:

1)将href属性中出现的所有-替换为一些预定义的"word"-不包括-的字符组合。这可以通过preg_replace_callback完成。

2)用str_replace:

替换普通字符串
$result = str_replace('-', '', $source);

3)用-字符反向替换所有出现的"word"

$newString = str_replace('> - <', '><', $oldString);