【问题标题】:substr() function for array PHP数组 PHP 的 substr() 函数
【发布时间】:2013-09-05 07:48:07
【问题描述】:

我有一个代码可以生成字符串数组......现在我的问题是我需要对数组的每个结果进行 substr,但我认为数组不允许在 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 是数组...我需要 substr 每个 $matches 的结果

【问题讨论】:

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

标签: php substr implode


【解决方案1】:

你可以使用array_walk:

function fcn(&$item) {
   $item = substr(..do what you want here ...);
}

array_walk($matches, "fcn");

【讨论】:

  • 我可以将我的 $matches 数组放在 substr 中吗?我需要 substr 数组的每个结果@matches
  • @Bongsky,不,您不能将$matches 放入substr。您必须遍历数组并将 substr 应用于每个单独的元素。例如我给你的将更新$matches 数组。
  • 它什么都不做......因为我知道 substr 有第一个参数字符串......我的参数是什么?
  • @Bongsky 在我的示例中的fcn 函数中,$item 保存每个项目的值,因此您的调用类似于$item = substr($item, 5); 左右。
  • 我得到这个错误先生... substr() 期望参数 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);

阅读更多:

array_map

array_walk

【讨论】:

  • 你所在的地区意味着什么?参数是什么?
【解决方案3】:

要在数组中查找子字符串,我在生产站点上使用此函数,效果很好。

我将数组转换为集合,因为它更易于管理。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多