PHP:如何匹配文档中所有出现的正则表达式模式
我正在对文档进行一些数据修改,这些文档的内容中可能(或可能不 - 视情况而定)出现正则表达式模式。
我想编写一个 PHP 函数来处理文档 - 该函数的工作是返回文档中所有匹配模式声音的数组(如果存在),或者如果未找到匹配则返回一个空数组。
我确信这涉及使用 PHP 函数 preg_match_all,但是,我不明白preg_match_all返回的数组的格式。我只想返回匹配的字符串的一维(即非嵌套数组),如下所示:
<?php
$pattern = "^[h].[a-z]{3,4}";
$doc = file_get_contents('some_pathname');
function get_matching_patterns($pattern, $doc){
$out = array();
if (strlen($doc) && strlen($pattern)){
// not sure about this - I don't like the complicated nested array returned
// by preg_match-all
preg_match_all($pattern, $doc, $out);
}
return out;
}
?>
I am doing some data munging on documents which may (or may not - as the case may be) have ocurrence(s) of a regular expression pattern in their content.
I would like to write a PHP function to use to process the documents - the job of the function is to return an array of all matching patterns sound in the document (if they exist), or to return an empty array if no matches were found.
I am sure that this involves using the PHP function preg_match_all, however, I do not understand the format of the array returned by preg_match_all. I simply want to return a 1 dimensional (i.e. non-nested array) of the strings that match as follows:
<?php
$pattern = "^[h].[a-z]{3,4}";
$doc = file_get_contents('some_pathname');
function get_matching_patterns($pattern, $doc){
$out = array();
if (strlen($doc) && strlen($pattern)){
// not sure about this - I don't like the complicated nested array returned
// by preg_match-all
preg_match_all($pattern, $doc, $out);
}
return out;
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$out[0]
$out[0]