如何在< br/>上爆炸字符串标签 [英] How to explode a string on <br/> tag

查看:96
本文介绍了如何在< br/>上爆炸字符串标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似以下的字符串

I have a string like following

Overall Queen Poster <br /> Queen Poster Headboard:<br /> Queen Poster <br /> Queen Footboard  <br /> Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs.

如何在
标记上爆炸它,以便我可以在数组中获取值?

How to explode it on
tag so that I can get the values in an array?

我尝试过

   $myString =  "Overall Queen Poster <br /> Queen Poster Headboard:<br /> Queen Poster <br /> Queen Footboard  <br /> Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs";
    $myArray = explode("\n",$myString);
    print_r($myArray);

但没有得到正确的结果.

But not getting correct result.

推荐答案

这是因为<br />!= \n.

您可以使用正则表达式将其拆分,以确保获得所有BR标签(<br><br /><br/><br class="break"><BR>等)

You can use regex to split it, to make sure that you get all the BR tags (<br>, <br />, <br/>, <br class="break">, <BR> etc.)

代码:

<?php
    $myString = 'Overall Queen Poster <br /> Queen Poster Headboard:<br /> Queen Poster <br /> Queen Footboard  <br /> Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs.';

    $myArray = preg_split('/<br[^>]*>/i', $myString);

    print_r($myArray);
?>

输出:

Array
(
    [0] => Overall Queen Poster 
    [1] =>  Queen Poster Headboard:
    [2] =>  Queen Poster 
    [3] =>  Queen Footboard  
    [4] =>  Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs.
)

演示

限制:

将拆分以br开头的所有HTML标记.这意味着,如果您创建自己的标签(例如<breadcrumb>),则会错误地将其视为换行符.

Will split on any HTML tags that start with br. Meaning that if you made your own tag, such as <breadcrumb>, this would mistakenly be seen as a line break.

替代:

  • explode('<br />', $myString),如果您确定标记将始终完全是<br />
  • preg_split('/<br\s*/?>/i', $myString),如果您具有诸如<breadcrumb>之类的标记,并且在任何<br>标记中没有任何属性.
  • explode('<br />', $myString) if you're sure that your tags will always be exactly <br />
  • preg_split('/<br\s*/?>/i', $myString) if you have tags such as <breadcrumb> and don't have any attributes in any <br> tag.

其他笔记:

如果您不想在匹配项中使用空格,则可以将正则表达式更改为/<br[^>]*>\s*/i,该匹配项也将匹配匹配项后的所有空格字符.或者,您可以通过$myArray = array_map('ltrim', $myArray);$myArray = array_map('ltrim', $myArray);来运行它.

If you don't want white-space in your matches, you can change your regex to /<br[^>]*>\s*/i which will also match any white-space characters after the match. Alternatively, you can run it through ltrim with $myArray = array_map('ltrim', $myArray);.

这篇关于如何在&lt; br/&gt;上爆炸字符串标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆