如何在 PHP 中的字符串中获取所有美元符号及其后的文本

How to get all dollar sings and the text after it in a string in 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})(.*?)(?=$|$)

Regex Demo

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 Demo

注意 :- 您需要的结果在 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);

DEMO