Reputation: 2968
I have a string like
HCl3C24
I want to break this string in php like
array(0 => H , 1 => Cl, 2 => 3 , 3 => C, 4 => 24)
Right now I am trying :
$matches = array();
$string = "HCl4";
preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);
print_r($matches[0]);
It's not working for characters but numbers. Could anyone please help me here ?
Upvotes: 3
Views: 57
Reputation: 396
You can also access each char of that string by treating it as an array:
$string = "HCl4";
echo $string[0] // prints H
echo $string[1] // prints C
echo $string[2] // prints l
echo $string[3] // prints 4
Upvotes: 0
Reputation: 66488
use this regex:
/([0-9]+|[a-zA-Z])/
if you want [ "H", "Cl", 3, "C", 24 ]
then
/([0-9]+|[A-Z][a-z]*)/
Upvotes: 5