Mohamed Abd El Rahman
Mohamed Abd El Rahman

Reputation: 293

splitting string with regular expression in php using preg_split

I am looking for a regular expression (using preg_split()) that can be used to split the following string:

hello<span id="more-32"></span>world                 

Desired result:

$var[0]=hello 
$var[1]=world

I tried using this code put it didn't work

preg_split('/<span id="more-\d+"></span>/','hello<span id="more-32"></span>world')

Upvotes: 1

Views: 305

Answers (1)

Programmer.zip
Programmer.zip

Reputation: 809

First: You should escape the fore slash by a backslash.

Second: You should put the semicolon at the end of code.

This will work:

    <?php
    $string = 'hello<span id="more-32"></span>world';
    $pattern = '/<span id="more-\d+"><\/span>/';

    $out = preg_split($pattern,$string);

?>

Print the splitted string:

    foreach ($out as $value) {
    echo $value . '<br />'; 
}

Output:

hello
world

or:

print_r($out);

Output:

Array (
     [0] => hello 
     [1] => world 
) 

Upvotes: 1

Related Questions