使用PHP函数格式化字符串的意外结果

时间:2014-09-26 11:34:38

标签: php

我正在尝试按如下方式获取输入字符串:

示例输入

  <p>
    In spite of how delightfully smooth the full-grain leather may be,
    it still provides quite a bit of durability to the upper of this
    Crush by Durango women&#39;s Western boot. Everything about this
    pull-on boot is stunning; you have the floral embroidery, the pop
    of metallic and a stylish x toe. To make these 12&rdquo; floral
    boots ease to get on, Durango added two very sturdy pull straps
    next to the boot&rsquo;s opening.</p>
<ul>
    <li>
        2 1/4&quot; heel</li>
    <li>
        Composition rubber outsole with vintage finish</li>
    <li>
        Cushion Flex insole</li>
</ul>

并生成以下输出:

输出字符串

In spite of how delightfully smooth the full-grain leather may be,
it still provides quite a bit of durability to the upper of this Crush by
Durango women's Western boot. Everything about this pull-on boot is stunning;
you have the floral embroidery, the pop of metallic and a stylish x toe.
To make these 12” floral boots ease to get on, Durango added two very sturdy
pull straps next to the boot’s opening.

2 1/4" heel
Composition rubber outsole with vintage finish
Cushion Flex insole

我有以下功能:

功能

function cleanString($str)
{
    $content = '';

    foreach(preg_split("/((\r?\n)|(\r\n?))/", strip_tags(trim($str))) as $line) {
    $content .= " " . trim($line) . PHP_EOL;
    }

    return $content;
}

此函数返回In spite of how delightfully smooth the full-grain leather may be并修剪字符串的其余部分。

有人可以解释如何改变功能以产生上述输出吗?

2 个答案:

答案 0 :(得分:1)

如果我理解你的要求,你可以在php中使用strip_tags()函数。

更多http://php.net/manual/en/function.strip-tags.php

答案 1 :(得分:0)

你遇到的问题是因为preg_split()。这导致字符串在正则表达式的匹配上“爆炸”,意味着第一部分仅返回,并“修剪”其余部分。

这样的事情就足够了

<?php

$s = "  <p>
    In spite of how delightfully smooth the full-grain leather may be,
    it still provides quite a bit of durability to the upper of this
    Crush by Durango women&#39;s Western boot. Everything about this
    pull-on boot is stunning; you have the floral embroidery, the pop
    of metallic and a stylish x toe. To make these 12&rdquo; floral
    boots ease to get on, Durango added two very sturdy pull straps
    next to the boot&rsquo;s opening.</p>
<ul>
    <li>
        2 1/4&quot; heel</li>
    <li>
        Composition rubber outsole with vintage finish</li>
    <li>
        Cushion Flex insole</li>
</ul>";

echo html_entity_decode( preg_replace("/<.+>/", "", trim($s) ) );

https://eval.in/198897