我是一个完整的菜鸟。我正在尝试提取Marine Corp.(没有来自$ data的引号。我已经搜索并搜索了如何处理双引号但是我的信息很短。有人可以提供一些指导吗?谢谢。
$data = '"title":{"rendered":"Marine Corp."}';
preg_match('/title":{"rendered":"(.*)"}/U',$data,$matches);
echo $matches[0]; //=> target
答案 0 :(得分:0)
你所追求的正则表达式是/\"title\"\:\{\"rendered\"\:\"(.*)\"\}/
$data = '"title":{"rendered":"Marine Corp."}';
preg_match('/\"title\"\:\{\"rendered\"\:\"(.*)\"\}/',$data,$matches);
$tmp = array_shift( $matches );
$tmp
将保留“Marine Corp.
”
另一方面,你似乎有一个JSON对象。如果你能做到这种情况,那就简单多了:
$data = '{"title":{"rendered":"Marine Corp."}}';
$tmp = json_decode($data, true);
var_dump($tmp['title']['rendered']);
答案 1 :(得分:0)
试试这个,
<?php
//If it is valid json then try with json_decode()
$json_string = '{"title":{"rendered":"Marine Corp."}}';
$json_array = json_decode($json_string,1);
echo "For Json Object:\n" . $json_array['title']['rendered']."\n";
//If it is just string pattern then with preg_match()
$re = '/"title":{"rendered":"(.*?)\.?"}/';
$str = '"title":{"rendered":"Marine Corp."}
"title":{"rendered":"Marine Police"}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo "\nFor String: \n";
foreach($matches as $match){
echo $match[1]."\n";
}
?>
<强>输出:强>
For Json Object:
Marine Corp.
For String:
Marine Corp
Marine Police
请参阅PHP演示:https://eval.in/973297
请参阅REGEX演示:https://regex101.com/r/GyGN9U/1
答案 2 :(得分:-1)
如果您不从$ data字符串中提取“Marine Corp”,请使用str_replace() 功能:
echo str_replace('Marine Corp.','',$ data);
结果:“title”:{“rendered”:“”}