如何在 PHP 中获取所有美元歌声及其后面的文本



marc 21 标签可能包含带有几个美元符号 $ 的行,例如:

$string='10$athis is text a$bthis is text b/$cthis is text$dthis is text d';

我试图匹配所有美元唱歌并在每次唱歌后获取文本,我的代码是:

preg_match_all("/\$[a-z]{1}(.*?)/", $string, $match);

输出为:

Array
(
    [0] => Array
        (
            [0] => $a
            [1] => $b
            [2] => $c
            [3] => $d
        )
    [1] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
        )
)

如何在每次唱歌后捕获文本,以便输出为:

Array
(
    [0] => Array
        (
            [0] => $a
            [1] => $b
            [2] => $c
            [3] => $d
        )
    [1] => Array
        (
            [0] => this is text a
            [1] => this is text b/
            [2] => this is text c
            [3] => this is text d
        )
)

您可以使用积极的前瞻来匹配字面$或字符串结尾,例如

($[a-z]{1})(.*?)(?=$|$)

正则表达式演示

PHP代码

$re = "/(\$[a-z]{1})(.*?)(?=\$|$)/"; 
$str = "10$athis is text a$bthis is text b/$cthis is text$dthis is text d"; 
preg_match_all($re, $str, $matches);

Ideone 演示

注意:- 您所需的结果以Array[1]Array[2]为单位。 Array[0]保留用于整个正则表达式找到的匹配项。

我认为一个简单的正则表达式就足够了

$re = '/($[a-z])([^$]*)/'; 
$str = "10$athis is text a$bthis is text b/$cthis is text$dthis is text d"; 
preg_match_all($re, $str, $matches);
print_r($matches);

演示

相关内容

  • 没有找到相关文章

最新更新