禁用行的PHP正则表达式以〜$开头

This is the code that I've created;

$abs = preg_grep('/^\~\$/gmi', $files);
var_dump($abs);
$json = json_encode($files);
echo($json);

Could anybody explain why it's not catching the second item in the following variable?

["Renewal Fee Reminder.docx","~$newal Fee Reminder.docx"]

edit:

Fixed, code is as follows (although only checks the first character);

$files = file_list($templateDir, '.docx');

function sortLineStarters($var) {
    return !($var[0] == '~');
}

$sortedFiles = array_filter($files, "sortLineStarters");

$json = json_encode($sortedFiles);
echo($json);

Why are you using regular expressions for that?

strpos($line, "~$") !== 0

would do the trick while being much more readable.

As for the regular expression itself:

  • I don't think the modifier g is supported. See the list of supported modifiers for more information.

  • You don't need a backslash before "~".

  • You don't need case insensitive flag, since the two characters you use don't depend on the case.

There are two problems. Firstly, g is an unknown modifier. Here is a list of all the valid php pattern modifiers: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Secondly, the $ in "~$newal Fee Reminder.docx" needs to be escaped. If not php will look for a variable named $newal and try to insert into the string.

The following code should work:

$files = ["Renewal Fee Reminder.docx","~\$newal Fee Reminder.docx"];
$abs = preg_grep('/^~\$/mi', $files);

Edit

If you want to match strings that do not start with ~$ then use the regex /^[^~][^\$]/mi