Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match returns empty array

Tags:

php

I always use preg_match and it always works fine, but today I was trying to get a content between two html tags <code: 1>DATA</code>

And I have a problem, which my code explains:

function findThis($data){
    preg_match_all("/\<code: (.*?)\>(.*?)\<\/code\>/i",$data,$conditions);
    return $conditions;
}

    // plain text
    // working fine

    $data1='Some text...Some.. Te<code: 1>This is a php code</code>';

    //A text with a new lines
    // Not working..

    $data2='some text..
    some.. te
    <code: 1>
    This is a php code
    ..
    </code>
    ';

    print_r(findThis($data1));

    // OUTPUT
    // [0][0] => <code: 1>This is a php code</code>
    // [1][0] => 1
    // [2][0] => This is a php code

    print_r(findThis($data2));

    //Outputs nothing!
like image 515
Alaa Gamal Avatar asked Jun 08 '26 01:06

Alaa Gamal


1 Answers

This is because the . character in PHP is a wildcard for anything but newline. Examples including newlines would break. What you want to do is add the "s" flag to the end of your pattern, which modifies the . to match absolutely everything (including newlines).

/\<code: (.*?)\>(.*?)\<\/code\>/is

See here: http://www.php.net/manual/en/regexp.reference.internal-options.php

like image 64
Sean Johnson Avatar answered Jun 10 '26 18:06

Sean Johnson