Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex to split content following specific pattern [closed]

Tags:

regex

php

I'm trying to write a regex in php to split the string to array. The string is

#000000 | Black #ffffff | White #ff0000 | Red

there can or cannot be space between the character and

|

so the regex needs to work with

#000000|Black #ffffff|White #ff0000|Red

For the second type of string this works.

$str = preg_split('/[\s]+/', $str);

How can I modify it to work with the first and second both strings?

Edit: Final output needs to be

Array ( [0] => Array ( [0] => #000000 [1] => Black ) [1] => Array ( [0] => #ffffff [1] => White ) [2] => Array ( [0] => #ff0000 [1] => Red) )
like image 440
geek geek Avatar asked Mar 11 '26 04:03

geek geek


1 Answers

I recommend just generating a single flat map of color names to hexadecimal values. Here is a way to do this with a single call to preg_split. We can try splitting on the following regex pattern:

\s*\|\s*|\s+(?=#)

This says to split on either \s*\|\s* or \s+(?=#), which is whitespace where what follows is the hash from a hexadecimal color literal.

$input = "#000000 | Black #ffffff | White #ff0000 | Red";
$array = preg_split("/\\s*\\|\\s*|\\s+(?=#)/", $input);

$map = array();
for ($i=0; $i < count($array); $i+=2) {
    $map[$array[$i]] = $array[$i+1];
}

print_r($map);

Array ( [#000000] => Black [#ffffff] => White [#ff0000] => Red )

I did not give the exact output you expect, but I also don't see any reason to have any array of associate arrays. If you really need that, then use this code:

$input = "#000000 | Black #ffffff | White #ff0000 | Red";
$array = preg_split("/\s*\|\s*|\s+(?=#)/", $input);

$output = array();
for ($i=0; $i < count($array); $i+=2) {
    $map = array();
    $map[$array[$i]] = $array[$i+1];
    $output[count($output)] = $map;
}

print_r($output);

Array ( [0] => Array ( [#000000] => Black ) [1] => Array ( [#ffffff] => White )
    [2] => Array ( [#ff0000] => Red ) )
like image 110
Tim Biegeleisen Avatar answered Mar 12 '26 16:03

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!