[英]regular expression word preceded by char
I want to grab a specific string only if a certain word is followed by a =
sign. 我只想在特定字词后接
=
符号时抓取特定字符串。
Also, I want to get all the info after that =
sign until a /
is reached or the string ends. 另外,我想在
=
符号之后获取所有信息,直到到达/
或字符串结束。
Let's take into example: 让我们举个例子:
somestring.bla/test=123/ohboy/item/item=capture
somestring.bla /测试= 123 / ohboy /产品/产品=捕获
I want to get item=capture
but not item alone. 我想获得
item=capture
但不想单独获得。
I was thinking about using lookaheads but I'm not sure it this is the way to go. 我当时正在考虑使用先行方式,但不确定是否要这样做。 I appreciate any help as I'm trying to grasp more and more about regular expressions.
感谢我在尝试越来越多地了解正则表达式方面的帮助。
[^/=]*=[^/]*
will give you all the pairs that match your requirements. 会给您所有符合您要求的对。
So from your example it should return: 因此,从您的示例中,它应该返回:
test=123
测试= 123
item=capture
项目=捕获
If you want to capture item=capture
, it is straightforward: 如果要捕获
item=capture
,那么很简单:
/item=[^\/]*/
If you want to also extract the value, 如果您还想提取值,
/item=([^\/]*)/
If you only want to match the value, then you need to use a look- behind . 如果你只是想匹配的价值,那么你需要后面使用look-。
/(?<=item=)[^\/]*/
EDIT: too many errors due to insomnia. 编辑:由于失眠过多的错误。 Also, screw PHP and its failure to disregard separators in a character group as separators.
同样,拧紧PHP及其无法忽略字符组中的分隔符作为分隔符的问题。
Here is a function I wrote some time ago. 这是我前一段时间编写的函数。 I modified it a little, and added the
$keys
argument so that you can specify valid keys: 我对其进行了一些修改,并添加了
$keys
参数,以便您可以指定有效的密钥:
function getKeyValue($string, Array $keys = null) {
$keys = (empty($keys) ? '[\w\d]+' : implode('|', $keys));
$pattern = "/(?<=\/|$)(?P<key>{$keys})\s*=\s*(?P<value>.+?)(?=\/|$)/";
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
foreach ($matches as & $match) {
foreach ($match as $key => $value) {
if (is_int($key)) {
unset($match[$key]);
}
}
}
return $matches ?: FALSE;
}
Just trow in the string and valid keys: 只需输入字符串和有效键即可:
$string = 'somestring.bla/test=123/ohboy/item/item=capture';
$keys = array('test', 'item');
$keyValuePairs = getKeyValue($string, $keys);
var_dump($keyValuePairs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.