Kivylius
Kivylius

Reputation: 6567

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

File1.txt

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

.....

print "I require coffee in the morning" //problem

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

I just want testing this out and de/test/as.pen to return in an array for the first example.

Is this possible? will there be a lot of problems with this?

Upvotes: 1

Views: 66

Answers (3)

revo
revo

Reputation: 48751

^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

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

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

Upvotes: 0

anubhava
anubhava

Reputation: 786041

You can use this regex:

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

Upvotes: 1

Related Questions