简体   繁体   English

正则表达式以查找值并以PHP返回

[英]Regular expression to find a value and return it in PHP

I've been trying to figure this out for 2 hours now with no success. 我已经尝试了2个小时,但没有成功。 Its a bit complicated for me i guess. 我猜这对我来说有点复杂。 I am trying to parse a script file in PHP and return some values to the user. 我试图解析PHP中的脚本文件,并向用户返回一些值。 The ones i want are like this: 我想要的是这样的:

_ value = object runFunction blah blah blah _ =对象runFunction等等等等

Basically what i want is (in an algorithm): 基本上我想要的是(在算法中):

  • IF case-insensitive runFunction is found in the line (because it might be runfunction) 如果在该行中发现不区分大小写的runFunction(因为它可能是runfunction)
  • AND the line starts with _ (underscore) (or if possible before the = there is a value that starts with _ to be sure of the result) AND行以_(下划线)开头(或者如果可能,在=之前有一个以_开头的值以确保结果)
  • THEN return that underscore value before the = to me. 然后将=之前的下划线值返回给我。

Usually 99.9% the format is like this...But there are small cases it can be like this: 通常99.9%的格式是这样的...但是在少数情况下,它可能是这样的:

_ value = _object runFunction blah blah blah (in case the _ after the = messes things up). _ value = _object runFunction等等等等(如果_之后的_弄乱了东西)。

Any help here :) ? 这里有什么帮助吗? Thanks 谢谢

try something like: 尝试类似:

$str = 'YOUR FILE CONTENTS HERE';
$match = preg_match_all('/(_[a-zA-Z0-9_]+) ?= ?[a-zA-Z0-9_]+ runFunction/s',$str,$matches);

var_dump($matches);

you'll probably need to add the multiline flag. 您可能需要添加多行标志。

How about 怎么样

if (preg_match('/^_([^=]+?)(?=\s*=).*runfunction/im', $subject, $regs)) {
    $result = $regs[1];
} else {
    $result = "";
}

You can exclude the initial "start" anchor is your underscore might not be at the beginning of the line 您可以排除初始的“开始”锚点,因为您的下划线可能不在行首

Here is the regex by itself. 这是正则表达式本身。 The results are in capturing group 1 结果在捕获组1中

^_([^=]+?)(?=\s*=).*runfunction

The regex look for beginning of line match the first underscore capture everything that is not an '=' into capturing group 1 provided it is followed by 0 or more spaces and an equal sign. 正则表达式查找行首匹配第一个下划线,将不是'='的所有内容捕获到捕获组1中,条件是后面跟有0个或多个空格和等号。 then capture everything up to a runfunction. 然后捕获所有内容,直到运行功能。

Case insensitive and multiline options need to be set 需要设置不区分大小写和多行的选项

If the first underscore does not need to be at the beginning of the line, eliminate the anchor. 如果第一个下划线不必在行的开头,则消除锚点。

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

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