Q:
How do I disab
Q:
How to use .cl
1. Field of the In
#pragma once
#incl
Bacteriophage T4 h
In the present sta
Ceramic is a commo
The first-ever dra
Q:
Why does this Q:
how do i split this string in PHP
I have the following string
"C3L6H6O0 H2O0O3 C6H6O2 CO2CO2 C3H4O CH3OH"
How would I go about splitting these values into separate fields and making them an array so I can parse them later?
A:
explode() can do what you want, and you can do something like:
$string = "C3L6H6O0 H2O0O3 C6H6O2 CO2CO2 C3H4O CH3OH";
$split = explode(" ", $string);
foreach ($split as $entry) {
if (strpos($entry, "O") !== false) { // skip the ones that start with "O"
$parts[] = trim($entry);
}
}
This will give you the following:
array('C3L6H6O0 ', ' H2O0O3 ', ' C6H6O2 ', ' CO2CO2 ', ' C3H4O ', ' CH3OH');
Is this what you wanted?
I hope this helps.
A:
use the array_filter
$data= explode(" ", "C3L6H6O0 H2O0O3 C6H6O2 CO2CO2 C3H4O CH3OH")
print_r(array_filter($data,function($val) {return strpos($val, "C") === false;}));
// will output as
array (
0 => "C3L6H6O0 " ,
1 => " H2O0O3 " ,
2 => " C6H6O2 CO2CO2 ",
3 => " C3H4O " ,
4 => " CH3OH"
)
i am not sure about your requirement so this is what i get.
A:
You could try the following regex. \s matches space. \S matches everything else. If you want to match the last letter O (uppercase or lowercase) and space use [a-zA-Z0-9]+$
\s*(\S)\s*[a-zA-Z0-9]+$
Explanation
\s* match zero or more white space characters
(\S) match and capture a single non-whitespace character, i.e. a string containing H2O0O3
\s* match again zero or more white space characters
[a-zA-Z0-9]+$ match all uppercase letters/lowercase letters/numbers till the end of the string (that is to say, matching everything till the end of the string)
Test it here.
Code
$string = "C3L6H6O0 H2O0O3 C6H6O2 CO2CO2 C3H4O CH3OH";
preg_match_all('/\s*(\S)\s*[a-zA-Z0-9]+$/', $string, $result);
foreach($result as $value){
print_r($value);
}
Outputs
Array ( [0] => C3L6H6O0 [1] => H2O0O3 [2] => C6H6O2 [3] => CO2CO2 [4] => C3H4O [5] => CH3OH )
Also see this post on creating Regex from scratch to understand better how it works.
A:
try this with the help of a simple regular expression (e.g. \b(C(?!\d)))(?:(?!\d)O|O(?!\d))(?:\d+(?:\.\d+)?)\b. if I got you right:
$string = "C3L6H6O0 H2O0O3 C6H6O2 CO2CO2 C3H4O CH3OH";
$regexp = '~\b((?:C(?!\d)))(?:(?!\d)O|O(?!\d))(?:\d+(?:\.\d+)?)\b~';
preg_match_all($regexp, $string, $matches);
if ($matches) {
var_dump($matches[0]);
}
output:
array (size=7)
0 => string 'C3L6H6O0' (length=10)
1 => string ' H2O0O3 ' (length=10)
2 => string ' C6H6O2 CO2CO2 ' (length=13)
3 => string ' C3H4O ' (length=6)
4 => string ' CH3OH' (length=6)
5 => string ' ' (length=1)
see the results online at ideone.com:
[1]: http://ideone.com/vPJZUa
edit for more specific requirement you might just want to match O followed by a number but without the digits 0 to 9. The following will do:
$regexp = '~\b(C(?!\d))(O(?!\d))*\d~';