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!
2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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.
Thanks Sean, finally the ten minutes is end, and i am able to accept your answer..
Why i use ( /i ) ? i use it but i don't now the reason, i am beginner in regexp
Please see the link I posted for an explanation on regexp flags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.