使用PHP替换字符串中的空格

时间:2015-05-13 16:39:46

标签: php str-replace

我正在尝试用PHP中的字符串中的空格替换<br>,但它似乎不起作用。我将如何纠正我为完成这项工作所做的工作?

我尝试过的代码行如下:

    $keyword = str_replace("<br>", " ", getTextBetweenTags($html, "h4", "ctlAuthor"));

代码中返回的字符串如下所示:

Dörte Kreher<br>Humboldt-Universität<br>Institut für Mathematik

返回PHP页面的字符串如下:

Dörte KreherHumboldt-UniversitätInstitut für Mathematik

应该返回到PHP页面的所需字符串:

Dörte Kreher Humboldt-Universität Institut für Mathematik

这是getTextBetweenTags()函数:

function getTextBetweenTags($string, $tagname, $tagid)
{
    $dochtml = new DOMDocument();
    $dochtml->loadHTML($string);
    $prgs = $dochtml->getElementsByTagName($tagname);
    $pcls = array();

    foreach($prgs as $prg)
    {
        if ($prg->getAttribute('id') == $tagid){
            $pcls[] = $prg->nodeValue;
        }
    }
    return $pcls[0];
}

4 个答案:

答案 0 :(得分:3)

尝试使用非破坏空格html

$keyword = str_replace("<br>", "&nbsp;", getTextBetweenTags($html, "h4", "ctlAuthor"));

答案 1 :(得分:0)

试试这个,它取代了字符串

中的所有html代码

$keyword = preg_replace("#<[^>]+>#", ' ', getTextBetweenTags($html, "h4", "ctlAuthor"));

答案 2 :(得分:0)

为什么不使用strip_tags?即:

$keyword = strip_tags(getTextBetweenTags($html, "h4", "ctlAuthor"));
strip_tags
  

从字符串中删除HTML和PHP标记

string strip_tags ( string $str [, string $allowable_tags ] )
  

此函数尝试返回包含所有NULL字节,HTML和的字符串   PHP标记从给定的str中剥离。它使用相同的标签剥离   状态机作为fgetss()函数。

https://php.net/strip_tags

根据您的评论进行更新:

$string = "Dörte Kreher<br>Humboldt-Universität<br>Institut für Mathematik";
$notags =  preg_replace('/<[^>]*>/', ' ', $string );
echo $notags;

输出:

  

DörteKreherHumboldt-UniversitätInstitutfürMathematik

答案 3 :(得分:0)

因为字符串来自DOMDocument中元素的NodeValues,所以需要保留HTML。为了解决这个问题,代码行:

$pcls[] = $prg->NodeValue;

替换为:

$pcls[] = $prg->ownerDocument->saveHTML($prg);

然后HTML标签可以用所需的输出替换,如下所示:

$keyword = str_replace("<br>", " ", getTextBetweenTags($html, "h4", "ctlAuthor"));

相关问题