Re: how to explode or split or chunk in an efficient way
| From: | Jim Lucas | Date: | Thu, 24 Jul 2014 18:31:30 +0000 |
| Subject: | Re: how to explode or split or chunk in an efficient way | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-323658@lists.php.net to get a copy of this message | ||
On 07/24/2014 09:18 AM, Negin Nickparsa wrote:
I have a string which always has "C" then a number which it's length can
change anytime and then "P" and then a space and then a word
like:
echo "C60P1 Unit";
is it anyway to split the string by type?
from the manual I did this:
function multiexplode ($delimiters,$string) {
$ary = explode($delimiters[0],$string);
array_shift($delimiters);
if($delimiters != NULL) {
foreach($ary as $key => $val) {
$ary[$key] = multiexplode($delimiters, $val);
}
}
return $ary;
}
echo "C60P1 Unit";
$str="C60P1 Unit";
$delimiters = Array("C","P"," ");
$res = multiexplode($delimiters,$str);
echo '<pre>';
print_r($res);
echo '</pre>';
but it seems to me it is so complex for such a small string
does anything for type exist which I don't know about to for example just
grab the numbers?because I just care about the numbers here 60 and 1
seperately
Try this
<?php
$in = "C60P1 Unit";
$regex = "/C(?P<C>[0-9]+)P(?P<P>[0-9]+) (?P<D>.*)/";
preg_match($regex, $in, $m);
print_r($m);
?>
Array
(
[0] => C60P1 Unit
[C] => 60
[1] => 60
[P] => 1
[2] => 1
[D] => Unit
[3] => Unit
)
--
Jim Lucas
http://www.cmsws.com/
http://www.cmsws.com/examples/