简体   繁体   English

php中字符串的正则表达式,以逗号查找单词

[英]Regular Expressions for string in php to find the word in commas

I'm trying to write a Regexp for php to scan true files, the keyword is require and the string I want is in brackets "my string" (require would be reserved) example 我正在尝试为php写一个Regexp来扫描真实文件,关键字是require ,而我想要的字符串在方括号"my string" (需要保留)中

File1.txt FILE1.TXT

require "testing/this/out.js"
require "de/test/as.pen"
require "my_love.test"

.....

print "I require coffee in the morning" //problem
  • The requires will be at the top of the page. 需求将在页面顶部。
  • Follow the standard require "_String_" format 遵循标准require "_String_"格式

File2.txt FILE2.TXT

Class Ben extends Name

....

print "My good boss always extends my deadline" //problem
  • Extends would only be follow by class name 扩展名只能跟随类名
  • Is only one word and only one result 只有一个字,只有一个结果

// looping true and determining if class or if reg file by folder structure
$subject = "Code above";
$pattern = '/^require+""/i'; // Not sure of the correct pattern
preg_match($pattern, $subject, $matches);
print_r($matches);

I just want testing this out and de/test/as.pen to return in an array for the first example. 我只想testing this out然后de/test/as.pen返回第一个示例的数组。

Is this possible? 这可能吗? will there be a lot of problems with this? 会有很多问题吗?

您可以使用此正则表达式:

$pattern = '/^ *require +"([^"]+)"/i';
^require (['"])([.\w /]+)\1

match the result: 匹配结果:

preg_match('#^require (['"])([.\w /]+)\1#', $code, $match);

Explanation : 说明

^               #  Start of string
require         #  reserved word with an space after
(['"])          #  Quotations
(               #  Capturing group
    [.\w /]+    #   Any possible characters
)               #  End of capturing group
\1              #  Same quotation

Demo 演示

The idea is to skip content inside quotes: 这个想法是跳过引号内的内容:

$pattern = <<<'LOD'
~
(["']) (?> [^"'\\]++ | \\{2} | \\. | (?!\1)["'] )* \1 # content inside quotes
(*SKIP)(*FAIL)  # forces this possibility to fail
|
(?>^|\s)
require \s+ " ([^"]++) "
~xs
LOD;

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
print_r($matches);

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

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