首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >数组PHP的substr()函数

数组PHP的substr()函数
EN

Stack Overflow用户
提问于 2013-09-05 15:48:08
回答 3查看 20.7K关注 0票数 2

我有一个生成字符串数组的代码...现在我的问题是,我需要对数组的每个结果进行子串运算,但我认为在子串中不允许使用数组。

请帮助:

代码:

代码语言:javascript
运行
复制
<?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的每个结果进行子串

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-05 15:52:59

您可以使用array_walk

代码语言:javascript
运行
复制
function fcn(&$item) {
   $item = substr(..do what you want here ...);
}

array_walk($matches, "fcn");
票数 2
EN

Stack Overflow用户

发布于 2013-09-05 16:02:28

正确使用array_walk

代码语言:javascript
运行
复制
array_walk( $matches, substr(your area));

Array_map接受多个数组

代码语言:javascript
运行
复制
array_map(substr(your area),  $matches1, $origarray2);

在你的情况下

代码语言:javascript
运行
复制
 array_map(substr(your area),  $matches);

阅读更多信息:

array_map

array_walk

票数 2
EN

Stack Overflow用户

发布于 2019-02-17 18:27:59

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

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

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18630608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档