简体   繁体   English

使用preg_split在php中用正则表达式分割字符串

[英]splitting string with regular expression in php using preg_split

I am looking for a regular expression (using preg_split() ) that can be used to split the following string: 我正在寻找一个正则表达式(使用preg_split() ),该正则表达式可用于拆分以下字符串:

hello<span id="more-32"></span>world                 

Desired result: 所需结果:

$var[0]=hello 
$var[1]=world

I tried using this code put it didn't work 我尝试使用此代码将其无效

preg_split('/<span id="more-\d+"></span>/','hello<span id="more-32"></span>world')

First: You should escape the fore slash by a backslash. 第一:您应该在反斜杠前加反斜杠。

Second: You should put the semicolon at the end of code. 第二:您应该将分号放在代码末尾。

This will work: 这将起作用:

    <?php
    $string = 'hello<span id="more-32"></span>world';
    $pattern = '/<span id="more-\d+"><\/span>/';

    $out = preg_split($pattern,$string);

?>

Print the splitted string: 打印分割的字符串:

    foreach ($out as $value) {
    echo $value . '<br />'; 
}

Output: 输出:

hello
world

or: 要么:

print_r($out);

Output: 输出:

Array (
     [0] => hello 
     [1] => world 
) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM