我有一个会生成字符串数组的代码....现在我的问题是我需要对数组的每个结果进行substr但我认为数组不允许在substr ...中使用...
请帮助:
CODE:
<?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
的每个结果加下一个答案 0 :(得分:2)
您可以使用array_walk
:
function fcn(&$item) {
$item = substr(..do what you want here ...);
}
array_walk($matches, "fcn");
答案 1 :(得分:2)
正确使用array_walk
array_walk( $matches, substr(your area));
Array_map接受多个数组
array_map(substr(your area), $matches1, $origarray2);
在你的情况下
array_map(substr(your area), $matches);
了解更多:
答案 2 :(得分:0)
要在数组中查找子字符串,我在生产站点上使用了此功能,效果很好。
我将数组转换为集合,因为它更易于管理。
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
。