3

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!
Quill
  • 2,729
  • 1
  • 33
  • 44
Alaa Gamal
  • 1,135
  • 7
  • 18
  • 28
  • The `.*` placeholder will not match newlines, unless you specify the 'dotall' modifier `/s`. – mario Jun 24 '12 at 23:09
  • 1
    possible duplicate of [How do I match any character across multiple lines in a regular expression?](http://stackoverflow.com/questions/159118/how-do-i-match-any-character-across-multiple-lines-in-a-regular-expression) – mario Jun 24 '12 at 23:10

1 Answers1

6

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

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
  • Thank you very much Sean Johnson, it's now working fine.. but another question, if i used this function with a very long text, i will get error? is there a limit? if so, How can i increase the limit size? – Alaa Gamal Jun 24 '12 at 23:14
  • The limit is however much memory you allocate to PHP. You'll have to be dealing with some really large data to run into that limit. – Sean Johnson Jun 24 '12 at 23:16
  • Thanks Sean, finally the ten minutes is end, and i am able to accept your answer.. – Alaa Gamal Jun 24 '12 at 23:20
  • Why i use ( /i ) ? i use it but i don't now the reason, i am beginner in regexp – Alaa Gamal Jun 24 '12 at 23:25
  • Please see the link I posted for an explanation on regexp flags. – Sean Johnson Jun 24 '12 at 23:27