【问题标题】:php split string by paragraph doesn't workphp按段落拆分字符串不起作用
【发布时间】:2018-06-23 15:58:24
【问题描述】:

我在按段落分割字符串时遇到了一些麻烦。

我在 $item->description 中有一个字符串,但它似乎没有做我需要的事情。

我的代码:

$text = explode("</p>", $item->description);
var_dump($text);

它只输出所有文本的位置,而不是进行拆分:

array(1) { [0]=> string(726) "<b>Requirements</b> <p>A zeal towards learning to learn 
as a priority. A sound knowledge of Internet and Browsing!</p> <b>Description</b> <p>The 
course DIGITAL SKILLS FOR TEACHERS inherits the requirements for being a ROCKSTAR 
Teachers with competency towards excellence within classrooms on narration with experience 
and making a wow feature a continuous activity in classrooms on priority. The course 
modules the expertise to imbibe for all teachers towards excellence with the adoption 
of technology in a big very way!</p> <b>Who is the target audience?</b> <p>Any individual 
who feels teaching is Sharing. A must for all Educators.</p>" }

有人可以帮助我吗?谢谢!

【问题讨论】:

  • 3v4l.org/mB7YW 无法复制
  • 测试时对我有用
  • 您使用的是什么版本的 PHP?文本可以是 UTF-8 吗?
  • @RiggsFolly 我使用的是 7.2.5 版本并检查了字符串,它给了我 ASCII。

标签: php split explode


【解决方案1】:

检查这个:-

$text = $item->description ;
$arr = explode("</p>", $text);
echo "<br>".$arr[0] ;

希望它不会出现任何问题。

【讨论】:

  • 这个解决方案的输出与我的主要问题相同。
  • 你运行了吗?请再次检查并告诉我。
  • 是的,我运行它。也许我的代码在其他地方有一些不好的地方。也许会更多/更少地做另一个节目。
  • 你能在爆炸前回显 item->description 字符串并检查结果吗?
  • Echoing item->description 返回纯文本。
【解决方案2】:

如果你想得到纯文本,那么你可以使用strip_tags 函数。它将从您的文本中删除所有 html 标签,包括段落标签。

例如:

/** Replace the <b> tag with placeholder */
$text = str_replace("<b>", "$", $item->description);
/** Replace the <\b> tag with placeholder */
$text = str_replace("<\b>", "^", $item->description);
/** Remove html from the text */
$text = strip_tags($text);
/** Replace placeholder with <b> tag */
$text = str_replace("$", "<b>", $item->description);
/** Replace placeholder with <\b> tag */
$text = str_replace("^", "<\b>", $item->description);

您也可以使用preg_match_all 函数。它将提取段落标签之间的所有文本。例如:

/** The text between paragraph tags is extracted using regular expression */
preg_match_all("/<p>(.*)<\/p>/iU", $item->description, $matches);
/** Each element of $text array contains text within a paragraph */
$text  = $matches[1];

【讨论】:

    【解决方案3】:

    使用这种格式:-

    $text = explode(PHP_EOL, $item->description);
    

    希望这会奏效。

    【讨论】:

    • 您没有检查我的代码和实际文本,并给出了否定的答复。此处上传的文字除了“p”标签外,双码内还有换行,表示换行数多于段落数。所以更正双引号内的文本并再次检查我的代码。
    【解决方案4】:

    您也可以使用此代码:-

    $text = preg_split('/\r\n|\r|\n/', $item->description) ;
    echo $text[0] ;
    

    【讨论】:

    • 我的猜测是要么他们不感兴趣,因为这些将在 HTML 中被忽略,或者他们稍后会想要删除换行符而不分割换行符上的任何内容
    • 是的。这里的目标是创建一个简单的“预览”。在第一段结束之前,预览应该是可见的。真的不明白为什么它不起作用:(
    • 我不知道您为什么对我的正确解决方案做出否定的回应。请检查我的更新并检查您是否会获得所需的输出。
    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多