我有一个字符串$newstring
,其中加载的行看起来像:
<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009 <br>
我想使用<tt>
和<br>
作为分隔符来分解$newstring
。
我如何使用preg_split()
或其他任何东西来爆炸它?
好吧,我在Nexus 7上,我发现在平板电脑上回答问题并不太优雅,但不管怎样,你都可以使用preg_split
使用以下正则表达式来完成这项工作:
<'/?tt>|</?br>
请参阅此处的正则表达式:http://www.regex101.com/r/kX0gE7
PHP代码:
$str = '<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br>';
$split = preg_split('@<'/?tt>|</?br>@', $str);
var_export($split);
阵列$split
将包含:
array (
0 => '',
1 => 'Thu 01-Mar-2012',
2 => ' 7th of Atrex, 3009',
3 => ''
)
(请参见http://ideone.com/aiTi5U)
您应该试试这个代码。。
<?php
$keywords = preg_split("/'<tt'>|'<br'>/", "<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009 <br>");
print_r($keywords);
?>
查看CodePad示例。
如果要包含</tt>
,请使用。。<'/?tt>|<br>
。请参见示例。
试试这个代码。。
<?php
$newstring = "<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br>";
$newstring = (explode("<tt>",$newstring));
//$newstring[1] store Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br> so do opration on that.
$newstring = (explode("<br>",$newstring[1]));
echo $newstring[0];
?>
output:-->
Thu 01-Mar-2012</tt> 7th of Atrex, 3009
如果<tt>
和<br/>
标记是字符串中唯一的标记,那么像这样的简单正则表达式就可以了:
$exploded = preg_split('/'<[^>]+'>/',$newstring, PREG_SPLIT_NO_EMPTY);
表达式:
分隔符分别以<
和>
开始和结束
在这些字符之间,至少需要1个[^>]
(这是除关闭的>
之外的任何字符
PREG_SPLIT_NO_EMPTY
这是一个常量,传递给preg_split
函数,避免数组值为空字符串:
$newString = '<tt>Foo<br/><br/>Bar</tt>';
$exploded = preg_split('/'<[^>]+'>/',$newstring);
//output: array('','Foo','','Bar',''); or something (off the top of my head)
$exploded = preg_split('/'<[^>]+'>/',$newstring, PREG_SPLIT_NO_EMPTY);
//output: array('Foo', 'Bar')
然而,如果您处理的标记或变量输入(如用户提供的(不止这两个,那么您最好解析标记。查看php的DOMDocument
类,请参阅此处的文档。
PS:要查看实际输出,请尝试echo '<pre>'; var_dump($exploded); echo '</pre>';
function multiExplode($delimiters,$string) {
return explode($delimiters[0],strtr($string,array_combine(array_slice($delimiters,1),array_fill(0,count($delimiters)-1,array_shift($delimiters)))));
}
EX:$values=multiExplode(数组(",">
"(,$your_string(;
下面是一个带有示例的自定义函数。
http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/