Php 从字符串中提取数据
如何从字符串中提取此部分,如:Php 从字符串中提取数据,php,regex,Php,Regex,如何从字符串中提取此部分,如: $str= 'We have new Call Request: Reference = 55823014, Name = Amal, Mobile = 111111' 使用正则表达式来提取它 reference | 55823014 Name | Amal Mobile | 1111111 这会给你 $str= 'We have new Call Request: Reference = 55823014, Name = Amal, M
$str= 'We have new Call Request: Reference = 55823014, Name = Amal, Mobile = 111111'
使用正则表达式来提取它
reference | 55823014
Name | Amal
Mobile | 1111111
这会给你
$str= 'We have new Call Request: Reference = 55823014, Name = Amal, Mobile = 111111';
preg_match('/Reference =(.*?), Name =(.*?), Mobile =(.*)/', $str, $m);
print_r($m);
//if you want to display an item at a time
echo "Reference = ".$m[1].PHP_EOL;
echo "Name = ".$m[2].PHP_EOL;
echo "Mobile = ".$m[3].PHP_EOL;
首先从字符串中删除文本“We have new Call Request:”。然后剩下包含键值对的主字符串。在此基础上,通过逗号将其分解为一个令牌数组,其中每个令牌包含一个键值对。然后循环遍历标记,并用等号“=”将键值分解出来。下面是它的代码:
Array
(
[0] => Reference = 55823014, Name = Amal, Mobile = 111111
[1] => 55823014
[2] => Amal
[3] => 111111
)
Reference = 55823014
Name = Amal
Mobile = 111111
好的,作为一种快速方法,这应该可以:
<?php
$str = 'We have new Call Request: Reference = 55823014, Name = Amal, Mobile = 111111';
$str = substr($str, strpos($str, ':') + 1);
$arr = explode(',', $str);
$data = array();
foreach ($arr as $item) {
$tokens = explode('=', $item);
$key = trim($tokens[0]);
$val = trim($tokens[1]);
$data[$key] = $val;
}
var_dump($data);
输出:
$str= 'We have new Call Request: Reference = 55823014,
Name = Amal, Mobile = 111111';
$str = strchr($str, "Reference");
$str = explode(',', $str);
foreach ($str as $item) {
$tokens = explode('=', $item);
$key = trim($tokens[0]);
$val = trim($tokens[1]);
echo $key . " | " . $val . PHP_EOL;
}
输出必须是变量还是数组?
Reference | 55823014
Name | Amal
Mobile | 111111