phpregexpreg-match-allmarc

How to get all dollar sings and the text after it in a string in PHP


A marc 21 tag may content a line with several dollar signs $ like:

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

I tried to match all the dollar sings and get the text after each sing, my code is:

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

the output is:

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

    [1] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
        )

)

How can capture the text after each sing so the output will be:

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
        )

)

Solution

  • You can use positive lookahead for matching \$ literally or end of string like

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

    Regex Demo

    PHP Code

    $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

    NOTE :- Your required result is in Array[1] and Array[2]. Array[0] is reserved for match found by entire regex.