phpdelimiterpreg-split

How to use Multiple Delimiter in preg_split()


I have this preg_split function with the pattern to search for any <br>

However, I would like to add some more pattern to it besides <br>.

How can I do that with the current line of code below?

preg_split('/<br[^>]*>/i', $string, 25);

Solution

  • PHP's preg_split() function only accepts a single pattern argument, not multiple. So you have to use the power of regular expressions to match your delimiters.

    This would be an example:

    preg_split('/(<br[^>]*>)|(<p[^>]*>)/i', $string, 25);
    

    If matches on HTML line breaks and/or paragraph tags.

    It is helpful to use a regex tool to test ones expressions. Either a local one or a web based service like https://regex101.com/

    The above slips the example text

    this is a <br> text
    with line breaks <br /> and
    stuff like <p>, correct?
    

    like that:

    Array
    (
        [0] => this is a
        [1] =>  text
    with line breaks
        [2] =>  and
    stuff like
        [3] => , correct?
    )
    

    Note however that for parsing HTML markup a DOM parser probably is the better alternative. You don't risk to stumble over escaped characters and the like...