PHP中用于数组的substr()函数

3

我可以帮您翻译如下内容,涉及it技术。

我有一段代码可以生成字符串数组... 现在我的问题是我需要截取数组中每个结果的子串,但我认为不能在substr中使用数组...

请帮忙解决:

代码:

<?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中的每个结果进行子字符串处理。

要将一个函数应用于数组中的所有项,请使用array_map(返回一个新数组)或array_walk(可以改变原始数组中的项)。 - undefined
首先,你的问题不够清楚。你想在哪个数组上使用substr函数?你尝试过了吗?对于任何数组应用函数的好解决方案是使用array_map函数。 - undefined
嗨@Jon,谢谢你的回复...如果你不介意,能给个示例代码吗?:3 - undefined
@BOSS 我需要对 $matches 数组中的每个结果进行子字符串处理... - undefined
3个回答

3
你可以使用 array_walk 函数:
function fcn(&$item) {
   $item = substr(..do what you want here ...);
}

array_walk($matches, "fcn");

我可以把我的$matches数组放在substr函数中吗?我需要对数组@matches的每个结果进行子字符串操作。 - undefined
@Bongsky,不,你不能在substr中放置$matches。你必须遍历数组,并对每个单独的元素应用substr。对于我给出的示例,你将更新$matches数组。 - undefined
它什么也不做...因为我知道substr函数的第一个参数是字符串...那么我的参数应该是什么? - undefined
在我的示例中,fcn 函数中的 $item 变量保存了每个项目的值,所以你的调用可能是类似这样的:$item = substr($item, 5); 或者其他类似的方式。 - undefined
先生,我遇到了一个错误... substr() 函数期望第一个参数是字符串,但给定的是数组。 - undefined

3

正确使用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函数


你的区域意味着什么?参数是什么? - undefined

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接