在PHP中使用正则表达式字符串来查找逗号中的单词

时间:2014-01-06 20:50:39

标签: php regex

我正在尝试编写一个用于php的Regexp来扫描真实文件,关键字是require,我想要的字符串在括号"my string"中(需要保留)示例

FILE1.TXT

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

.....

print "I require coffee in the morning" //problem
  • 要求将位于页面顶部。
  • 遵循标准require "_String_"格式

FILE2.TXT

Class Ben extends Name

....

print "My good boss always extends my deadline" //problem
  • 延伸只会跟着班级名称
  • 只有一个字,只有一个结果

// 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);

我只想让testing this outde/test/as.pen在第一个示例的数组中返回。

这可能吗?会有很多问题吗?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

^require (['"])([.\w /]+)\1

匹配结果:

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

说明

^               #  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

答案 2 :(得分:0)

想法是跳过引号内的内容:

$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);