Search code examples
phpregexpreg-split

php preg_split with special chars


$tags = preg_split('@ @', 'Hello World 1 2  3 45   54', NULL, PREG_SPLIT_NO_EMPTY);
print_r($tags);
$tags = preg_split('/ /', 'Hello World 1 2  3 45   54', NULL, PREG_SPLIT_NO_EMPTY);
print_r($tags);

$tags = preg_split('@/@', '1/2//3', NULL, PREG_SPLIT_NO_EMPTY);
print_r($tags);
$tags = preg_split('/\//', '1/2//3', NULL, PREG_SPLIT_NO_EMPTY);
print_r($tags);

Why is the last one not working?, what is exactly the difference of @ with / for building php regex?

thx for clarifications


Solution

  • the tool you are using, writecodeonline.com/php, is broken. If you change the default code to

    echo 'Hello\ World';
    

    it should output Hello\ World, not Hello World, as it does.

    This explains why '/\//' breaks: it is seen by this tool as '///', which is not a valid regex. Double backslashes are interpreted correctly, though: '/\\//' works (but that's because PHP "sees" '/\//', which is equivalent to '/\\//').

    One more check:

    echo strlen('///'), ' ', strlen('/\//'), ' ', strlen('/\\//');
    

    should print 3 4 4. On writecodeonline.com/php it prints 3 3 4.