Search code examples
phpsubstrimplode

substr() function for array PHP


I have a code that will produce array of strings.... now my problem is i need to substr each result of the array but i think array is not allowed to be used in substr...

please help:

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";
 }


 }
 ?>

The $matches there is the array... i need to substr each result of the $matches


Solution

  • you can use array_walk:

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