简体   繁体   English

使用正则表达式提取值

[英]Extract a value using regular expression

Say I have this string: fg_^"-kv:("value_i_want")frt . That string will stay constant except for value_i_want - which could change all the time. This little string is hidden within a huge string of data (constantly changing), I have saved in a PHP variable 假设我有以下字符串: fg_^"-kv:("value_i_want")frt 。除了value_i_want之外,该字符串将保持不变-该字符串可能随时更改。这个小字符串隐藏在巨大的数据字符串中(不断变化) ,我已经保存了一个PHP变量

Is there any I could do a Regular Expression on a string, let's say of 50000 characters to find that string (above) without knowing what the value_i_want is, and then saving the value in a variable - using PHP 有什么我可以对字符串进行正则表达式的例子,假设有50000个字符在不知道value_i_want是什么的情况下找到该字符串(上方),然后将值保存在变量中-使用PHP

You can just use strpos to find where the value you want is. 您可以只使用strpos查找所需的值在哪里。 You may need to tweak this a little, I haven't tested it. 您可能需要稍微调整一下,我还没有测试过。 $long_string is the string you are searching for a match in. $long_string是您要搜索匹配项的字符串。

$start = strpos($long_string, 'fg_^"-kv:("', 0);
$end = strpos($long_string, '")frt', $start);
$value_i_want = substr($long_string, $start+11, $end-$start-11);

Try this: 尝试这个:

if (preg_match_all('/(?<=fg_\^\"\-kv:\(\")[a-z_]+(?=\"\)frt)/', $yourstring, $matches)) {
  echo "Match was found <br />";
  echo $matches[0];
}

Pattern: (?<=fg_\\^\\"\\-kv:\\(\\")[a-z_]+(?=\\"\\)frt) 模式: (?<=fg_\\^\\"\\-kv:\\(\\")[a-z_]+(?=\\"\\)frt)

(?<=fg_\\^\\"\\-kv:\\(\\") - positive lookbehind assertion, means that searched string should be after exactly this string: fg_^"-kv:(" (?<=fg_\\^\\"\\-kv:\\(\\") -正向后断言,表示搜索的字符串应恰好在此字符串之后: fg_^"-kv:("

(?=\\"\\)frt) - positive lookahead assertion, means the same, but before: ")frt (?=\\"\\)frt) -正向超前断言,含义相同,但之前: ")frt

[a-z_]+ - the string you are looking for, may consist of one or more letter and underscores. [a-z_]+ -您要查找的字符串,可以包含一个或多个字母和下划线。 Change it for your needs. 根据您的需要进行更改。

Demo: https://regex101.com/r/vS7dI0/1 演示: https//regex101.com/r/vS7dI0/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM