Search code examples
phpsplitpreg-split

Convert split() to preg_split()


newbee here...

I'm trying to replace the split() functions in a website so I found preg_split() to use. First had to find out how the split() function works so I looked at this example at the php.net site:

<?php
// Delimiters may be slash, dot, or hyphen
$date = "04-30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>

The output was as expected: Month: 04; Day: 30; Year: 1973

So I thought it would be easy and just change it to:

<?php
// Delimiters may be slash, dot, or hyphen
$date = "04-30/1973";
list($month, $day, $year) = preg_split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>

Output: Month: 04-30/1973; Day: ; Year:

What is wrong in my thinking?


Solution

  • Just add some symbols to define start/end of regular expression. It can be ~, for example:

    $date = "04-30/1973";
    list($month, $day, $year) = preg_split('~[/.-]~', $date);
    echo "Month: $month; Day: $day; Year: $year<br />\n";
    

    Update:

    If your code works with / as regexp borders, then you have to escape / with a backslash:

    list($month, $day, $year) = preg_split('/[\/.-]/', $date);