问题
In the regular expression below, where does the i
modifier go so as to make the search terms $searchfor
case insensitive? It seems it won't work no matter where I place it.
$file = 'xml.xml';
$searchfor = '(<first>|<last>|<state>)';
header('Content-Type: text/plain');
$contents = file_get_contents($file);
$regExp = '/^'.$searchfor.'(.*)$/m';
if(preg_match_all($regExp, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
} else {
echo "No matches found";
}
Contents of xml.xml
<first>Micky</first>
<last>Mouse</last>
<state>CA</state>
<first>Donald</first>
<LAST>Duck</LAST>
<state>FL</state>
<FIRST>Gyro</FIRST>
<last>Gearloose</last>
<state>MA</state>
回答1:
You could add the case insensitive flag where the multi line is also specified /m
This line:
$regExp = '/^'.$searchfor.'(.*)$/m';
Could then be:
$regExp = '/^'.$searchfor.'(.*)$/mi';
回答2:
Note row $regExp = '/^'.$searchfor.'(.*)$/m';
in your code.
It "assembles" the content of regex (/.../
) and just after it
there is a place for options.
You put only m
there, so just add i
.
But it is not all. I am in doubt whether after the "initial" part you realy need to capture all the rest of the line.
Try slightly changed regex:
/^<(first|last|state)>([^<]+)<\/\1>$/mi
(\1
requires the same content as matched by the 1st capturing group).
The advantage is that the second capturing group will catch only Micky
,
Mouse
, CA
and so on, without the closing tag.
If you want to check which tag was before (the first capturing
group) this solution is also more elegant, as this group contains
only first
, last
or state
, without surrounding angle brackets.
回答3:
There are a few ways you could do it. In your current regex you could just use the i
modifier after your closing delimiter.
$regExp = '/^'.$searchfor.'(.*)$/mi';
https://regex101.com/r/31C9SK/2/
or you could use:
$regExp = '/(?i)^'.$searchfor.'(.*)$/m';
https://regex101.com/r/31C9SK/1/
which is the same but is easier for usage when regex doesn't have delimiters (grep
, etc.).
Another approach you could take is just converting both strings to lowercase with strtolower.
if(preg_match_all(strtolower($regExp), strtolower($contents), $matches)){
https://3v4l.org/MsJdV
来源:https://stackoverflow.com/questions/50888505/where-does-the-case-insensitive-modifier-go-in-this-regular-expression