在 PHP 中使用 preg_replace 获取特定字符串
Get particular string using preg_replace in PHP
我从一个包含以下值的文件中提取了文档注释块:
[0] => /**
* Shows this block on only the listed pages.
*/
[1] => /**
* Shows this block if the associated PHP code returns TRUE.
*/
[2] => /**
* Implements hook_help().
*/
[3] => /**
* Implements hook_theme().
*/
现在我需要提取所有在 Implements 之后具有“hook_*”的文本。
所以我的最终输出应该是一个数组,其值如下:
$hooks = array('hook_help', 'hook_theme');
我应该使用什么 preg_replace
表达式?
假设保存评论的数组是$comments
,下面会做:
$hooks = array();
foreach($comments as $comment) {
if (preg_match("/Implements (hook_\w+)\(\)/", $comment, $matches))
$hooks[] = $matches[1];
}
这将匹配具有单词 Implements 后跟 hook_ 和至少一个字母后跟 () 的文本。然后将在 $matches[1]
中存储第一个带括号的子模式,即 hooks_...
我从一个包含以下值的文件中提取了文档注释块:
[0] => /**
* Shows this block on only the listed pages.
*/
[1] => /**
* Shows this block if the associated PHP code returns TRUE.
*/
[2] => /**
* Implements hook_help().
*/
[3] => /**
* Implements hook_theme().
*/
现在我需要提取所有在 Implements 之后具有“hook_*”的文本。
所以我的最终输出应该是一个数组,其值如下:
$hooks = array('hook_help', 'hook_theme');
我应该使用什么 preg_replace
表达式?
假设保存评论的数组是$comments
,下面会做:
$hooks = array();
foreach($comments as $comment) {
if (preg_match("/Implements (hook_\w+)\(\)/", $comment, $matches))
$hooks[] = $matches[1];
}
这将匹配具有单词 Implements 后跟 hook_ 和至少一个字母后跟 () 的文本。然后将在 $matches[1]
中存储第一个带括号的子模式,即 hooks_...