how to separate a string in php
sometext( [key] => value which content number and alphabates )
from above,i want only value part by using explod开发者_StackOverflow中文版e function for only one time.Is it possible. or any other function is present in php.
You can do:
$arr = explode('=>',$str);
$arr = explode(')',$arr[1]);
echo "Value = ".$arr[0]; // prints: Value = abc123hfj
or using regex you can do:
$str = 'asns([this_is_key]=>abc123hfj)';
if(preg_match('/=>([^)]*)\)/',$str,$matches)) {
echo "Value = ".$matches[1]; // prints: Value = abc123hfj
}
If you want to use explode just once you can do:
$arr = explode('=>',chop($str,')'));
echo "Value = ".$arr[1]; // prints: Value = abc123hfj
If your goal is to get array (1 => "value", 2 => "which content number and alphabates");
You can just search first occurrence of a whitespace, and call two substr functions. Something like that
$string = 'value which content number and alphabates';
$result = array(substr($string, 0, strpos($string, ' ')), substr($string, strpos($string, ' ')+1));
print_r($result);
Or you can do explode and and implode exploded array, after unsetting array key 0, like so
$string = 'value which content number and alphabates';
$chunk = explode(' ', $string);
$result = array();
$result[] = $chunk[0];
unset($chunk[0]);
$result[] = implode(' ', $chunk);
print_r($result);
Or if you want to get just part "value" from your string, just use list
$string = 'value which content number and alphabates';
list($result) = explode(' ', $string);
echo $result;
精彩评论