Php 正则表达式。。。从字符串中提取特定单词
我有以下字符串,我想从中提取位置Php 正则表达式。。。从字符串中提取特定单词,php,regex,Php,Regex,我有以下字符串,我想从中提取位置 {"image_intro":"images\/slider\/lazic.jpg","float_intro":"","image_intro_alt":"Tuttlingen","image_intro_caption":"","image_fulltext":"images\/slider\/lazic.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""
{"image_intro":"images\/slider\/lazic.jpg","float_intro":"","image_intro_alt":"Tuttlingen","image_intro_caption":"","image_fulltext":"images\/slider\/lazic.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}
所以我需要一个单词Tuttlingen。。。没别的了
谁能告诉我PHP的正确正则表达式吗?这是一个格式很好的JSON字符串。使用
json\u decode()
会容易得多
$string = '{"image_intro":"images\/slider\/lazic.jpg","float_intro":"","image_intro_alt":"Tuttlingen","image_intro_caption":"","image_fulltext":"images\/slider\/lazic.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}';
$json = json_decode($string, true);
echo $json['image_intro_alt'];
更新:按照建议将匹配设置为惰性您可以在php中使用
json\u decode
reference$s=“Tuttlingen”代码>。不客气。是的,谢谢你提醒我。我总是忘记这一点。虽然这在技术上是正确的(最好的一种正确),但问题是明确地要求一个正则表达式。@apokryfos虽然OP想要一个正则表达式是正确的,但重要的是要记住正则表达式所涉及的开销要比解析器所产生的开销大得多。而且,在这种情况下,它的代码也更加简单和干净。不要只回答问题,想想如何教人们更好地编写代码。@apokryfos当问题明确要求使用正则表达式时,将字符串视为JSON并使用JSON\u decode()
达到所需的结果,我相信这比不必要地摆弄正则表达式更干净、更容易。显式的正则表达式请求可能只是因为OP不熟悉JSON/JSON\u decode()
,因为确实不需要在这个输入中使用正则表达式。非常感谢。。。我在整个网站上搜索json。。。但是如果你不知道这个词。。。没有办法。。。所以谢谢你,它确实比正则表达式好!
$str = '{
"image_intro": "images\/slider\/lazic.jpg",
"float_intro": "",
"image_intro_alt": "Tuttlingen",
"image_intro_caption": "",
"image_fulltext": "images\/slider\/lazic.jpg",
"float_fulltext": "",
"image_fulltext_alt": "",
"image_fulltext_caption": ""
}';
$res = null;
$regex = "/.*\"image\_intro\_alt\"\:\s*\"(.*?)\".*/";
preg_match($regex,$str,$res);
if (is_array($res) && isset($res[1])) {
echo $res[1]; //Echo or do whatever with it.
}