我有一个生成字符串数组的代码...现在我的问题是,我需要对数组的每个结果进行子串运算,但我认为在子串中不允许使用数组。
请帮助:
代码:
<?php
$file = 'upload/filter.txt';
$searchfor = $_POST['search'];
$btn = $_POST['button'];
$sum = 0;
if($btn == 'search') {
//prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
$result = implode("\n", $matches[0]);
echo $result;
}
else{
echo "No matches found";
}
}
?>那里的$matches是数组...我需要对$matches的每个结果进行子串
发布于 2013-09-05 15:52:59
您可以使用array_walk
function fcn(&$item) {
$item = substr(..do what you want here ...);
}
array_walk($matches, "fcn");发布于 2013-09-05 16:02:28
正确使用array_walk
array_walk( $matches, substr(your area));Array_map接受多个数组
array_map(substr(your area), $matches1, $origarray2);在你的情况下
array_map(substr(your area), $matches);阅读更多信息:
array_map
array_walk
发布于 2019-02-17 18:27:59
要在数组中查找子字符串,我在生产站点上使用此函数,效果很好。
我将数组转换为集合,因为它更易于管理。
public function substrInArray($substr, Array $array) {
$substr = strtolower($substr);
$array = collect($array); // convert array to collection
return $body_types->map(function ($array_item) {
return strtolower($array_item);
})->filter(function ($array_item) use ($substr) {
return substr_count($array_item, $substr);
})->keys()->first();
}这将返回第一个匹配的关键字,这只是一个可以修补的示例。如果未找到任何内容,则返回null。
https://stackoverflow.com/questions/18630608
复制相似问题