使用PHP解析字符串
我试图解析一个字符串,但我有一个困难的时间。下面是一个数据示例。我需要用粗体突出显示部分,以便在数据库中查找名称 [AZ-国内]Acme Technologies LLC-(84383)” 到目前为止,我已经尝试了以下几点:使用PHP解析字符串,php,regex,Php,Regex,我试图解析一个字符串,但我有一个困难的时间。下面是一个数据示例。我需要用粗体突出显示部分,以便在数据库中查找名称 [AZ-国内]Acme Technologies LLC-(84383)” 到目前为止,我已经尝试了以下几点: $string = '[AZ - Domestic] Acme Technologies LLC - (8484383)"'; $start = stripos($string, ']'); $end = strripos($string , '-'); echo sub
$string = '[AZ - Domestic] Acme Technologies LLC - (8484383)"';
$start = stripos($string, ']');
$end = strripos($string , '-');
echo substr($string + 2, $start, $end);
但这给了我这个结果:Acme Technologies LLC-(8484383)”但我真正需要的是这个Acme Technologies LLC。我已经尝试了我所知道的所有PHP函数来获得这个结果,但似乎无法做到这一点 如果字符串始终采用该格式,请执行以下操作:
$regex = '%\[.*\]\s(.*)\s-\s\(.*\)\"%';
$match = preg_match($regex, $string);
$company = $match[1];
$company
将包含您的公司名称
在这种情况下,正则表达式是解决此类问题的“必备工具”。我建议您下载一些类似于帮助您构造正则表达式的内容。substr的第二个参数不是子字符串的结束位置,而是它的长度。我们也要这样做:
substr($string, $start + 2, $end - $start - 3);
这里有三种不同的方法可以在单个函数调用中使用正则表达式: 代码:() 输出:
'Acme Technologies LLC'
'Acme Technologies LLC'
'Acme Technologies LLC'
'Acme Technologies LLC'
16 & 21
'Acme Technologies LLC'
由于我完全没有理由被否决,我将添加一些非正则表达式方法,这些方法也将在输入字符串上证明是成功的: 代码:() 两个函数调用:
$string = '[AZ - Domestic] Acme Technologies LLC - (8484383)"';
var_export(strstr(explode('] ',$string,2)[1],' -',true));
$string = '[AZ - Domestic] Acme Technologies LLC - (8484383)"';
$start=strpos($string,']')+2; // bump offset +2 to eliminate `] `
$length=strpos($string,' - (')-$start; // substract ending offset from starting offset to find length
echo "\n\n$start & $length\n";
var_export(substr($string,$start,$length));
三个函数调用:
$string = '[AZ - Domestic] Acme Technologies LLC - (8484383)"';
var_export(strstr(explode('] ',$string,2)[1],' -',true));
$string = '[AZ - Domestic] Acme Technologies LLC - (8484383)"';
$start=strpos($string,']')+2; // bump offset +2 to eliminate `] `
$length=strpos($string,' - (')-$start; // substract ending offset from starting offset to find length
echo "\n\n$start & $length\n";
var_export(substr($string,$start,$length));
*请注意,在搜索非字母字符时,strpos()
上不需要区分大小写。我还通过将指针设置为-(
)来避免从字符串的末尾匹配r
。通过将指针向字符串的前面延伸,我避免了执行额外的减法来计算$length
输出:
'Acme Technologies LLC'
'Acme Technologies LLC'
'Acme Technologies LLC'
'Acme Technologies LLC'
16 & 21
'Acme Technologies LLC'
p、 我在这些字符串值上使用
var_export()
来表示这样一个事实,即我的输出中没有前导空格或尾随空格可以修剪。你能提供更多的输入/输出示例吗?我对正则表达式很感兴趣,但这里有一个开始:@esqew我也尝试了echo substr($string+2,$start,$end)
这就从一开始就去掉了]**。我似乎无法摆脱**-(8484383)substr的最后一个参数应该是长度,而不是结束字符的位置。--也是的,使用正则表达式。strpos/substr是为那些不太懂的人准备的。第二个数字是长度,而不是位置。