在 PHP 上询问 REGEX
Ask about REGEX on PHP
我想要这个字符串:
{"48":"KAPAL GAGAK"}
使用 regex
成为 KAPAL GAGAK
。我使用
实现了这一点
/["0-9{:}]
但在
中使用它
{"51":"KAPAL GLORY / EX PAN MARINE 2"}
导致 KAPAL GLORY / EX PAN MARINE
而不是 KAPAL GLORY / EX PAN MARINE 2
,因为 regex
过滤了从 0 到 9 的所有数字。
执行此操作的正确方法是什么?
你的字符串看起来像 JSON
我建议使用 http://php.net/manual/en/function.json-decode.php
$json = '{"51":"KAPAL GLORY / EX PAN MARINE 2"}';
$array = json_decode( $json, true );
var_dump( current( $array ) ); // string(29) "KAPAL GLORY / EX PAN MARINE 2"
添加您选择的错误处理。
$tests = ['{"48":"KAPAL GAGAK"}', '{"51":"KAPAL GLORY / EX PAN MARINE 2"}', 'not pass throught'];
foreach($tests as $test){
// json_decode way
$obj = json_decode($test, true);
if($obj){
echo array_values($obj)[0]."\n";
}
// preg_match way
preg_match('/"([^"]*)"}/', $test, $matches);
if($matches){
echo $matches[1]."\n";
}
}
我想要这个字符串:
{"48":"KAPAL GAGAK"}
使用 regex
成为 KAPAL GAGAK
。我使用
/["0-9{:}]
但在
中使用它{"51":"KAPAL GLORY / EX PAN MARINE 2"}
导致 KAPAL GLORY / EX PAN MARINE
而不是 KAPAL GLORY / EX PAN MARINE 2
,因为 regex
过滤了从 0 到 9 的所有数字。
执行此操作的正确方法是什么?
你的字符串看起来像 JSON
我建议使用 http://php.net/manual/en/function.json-decode.php
$json = '{"51":"KAPAL GLORY / EX PAN MARINE 2"}';
$array = json_decode( $json, true );
var_dump( current( $array ) ); // string(29) "KAPAL GLORY / EX PAN MARINE 2"
添加您选择的错误处理。
$tests = ['{"48":"KAPAL GAGAK"}', '{"51":"KAPAL GLORY / EX PAN MARINE 2"}', 'not pass throught'];
foreach($tests as $test){
// json_decode way
$obj = json_decode($test, true);
if($obj){
echo array_values($obj)[0]."\n";
}
// preg_match way
preg_match('/"([^"]*)"}/', $test, $matches);
if($matches){
echo $matches[1]."\n";
}
}