substr() function for array PHP - 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

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

Proper use of array_walk
array_walk( $matches, substr(your area));
Array_map accepts several arrays
array_map(substr(your area), $matches1, $origarray2);
in your case
array_map(substr(your area), $matches);
Read more:
array_map
array_walk

To find a sub string in an array I use this function on a production site, works perfectly.
I convert the array to a collection because it's easier to manage.
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();
}
This will return the key from the first match, it's just an example you can tinker. Returns null if nothing found.

Related

find bad word using strpos from string

I have following php code to find bad word in a string.
It stop on first bad word found and return true.
The bad words are provided as comma separated list that is converted to array.
$paragraph = "We have fur to sell";
$badWords = "sis, fur";
$badWordsArray = explode(",", $badWords);
function strpos_arr($string, $array, $offset=0) { // Find array values in string
foreach($array as $query) {
if(strpos($string, $query, $offset) !== false) return true; // stop on first true result for efficiency
}
return false;
}
strpos_arr($paragraph, $badWordsArray);
The issue is it also returns true if bad word provided is a part of another word.
I prefer using strpos.
Please also suggest if there is any more efficient way to find bad words.
try this, with reqular expression:
$paragraph = "We have fur to sell";
$badWords = "sis, fur";
$badWordsArray = preg_split('/\s*,\s*/', $badWords, -1, PREG_SPLIT_NO_EMPTY);
var_dump($badWordsArray);
function searchBadWords($string, $array, $offset=0) { // Find array values in string
foreach ($array as $query) {
if (preg_match('/\b' . preg_quote($query, '/') . '\b/i', $string)) return true; // stop on first true result for efficiency
}
return false;
}
var_dump(searchBadWords($paragraph, $badWordsArray));
Explanation:
First. We want to correctly split our $badWords string:
$badWordsArray = preg_split('/\s*,\s*/', $badWords, -1, PREG_SPLIT_NO_EMPTY);
This way we will correctly split strings like "sis, fur" and "sis , fur" and even "sis , , fur" to an array('sis', 'fur').
Then we are performing regexp-search of exact word using \b meta-character. Which means word-boundary in terms of regular expression, that is position between a word-characted and a non-word-character.
Just include spaces in your search string.
$paragraph = "We have fur to sell";
$badWords = "sis, fur";
$badWordsArray = explode(",", $badWords);
function strpos_arr($string, $array, $offset=0) { // Find array values in string
$string = " ".$string." ";
foreach($array as $query) {
$query = " ".$query." ";
if(strpos($string, $query, $offset) !== false) return true; // stop on first true result for efficiency
}
return false;
}
strpos_arr($paragraph, $badWordsArray);

Getting function names from php file with preg_match_all

I have a file test.php:
public function editAction() {
//...
}
public function editGroupAction() {
//...
}
This is my code:
$source = "test.php";
$fh = fopen($source,'r');
while ($line = fgets($fh)) {
preg_match_all('/function(.*?)Action()/', $line, $matches);
var_dump($matches);
}
I want to get the functions that end with Action, but the result is empty. How do I get a result like this:
edit
editGroup
Your code can be simplified to this:
$fileName = 'test.php';
$fileContent = file_get_contents($fileName);
preg_match_all('/function(.*?)Action()/', $fileContent, $matches);
$functions = $matches[1];
Result ($functions):
Array
(
[0] => edit
[1] => editGroup
)
Following is your code with some changes...
First, check if anything was found, if so, add that to an array. Here is the working code:
$source = "test.php";
$fh = fopen($source,'r');
$m = array();
while ($line = fgets($fh)) {
if(preg_match_all('/function(.*?)Action()/', $line, $matches)){
$m[] = $matches[1][0];
}
}
Result ($m):
Array
(
[0] => edit
[1] => editGroup
)
Since preg_match_all returns the number of full pattern matches, you can use the return to check if anything was found. If you get a hit, add the wanted value to an array so you can get it later.
You were getting some empty results because not all lines will match ;)
Sidenote: As mentioned, you'll end up with something like string(5) " edit" (notice the white space). I don't know preg, so I can't fix it for you. What I can do is suggest you to change to $functions = array_map('trim', $matches[1]);
Not sure if that's what you want, but you should escape parentheses in regexp.
So here's your code with minor modifications:
<?php
$content = "public function editAction() public function editGroupAction()";
preg_match_all('/function(.*?)Action\(\)/', $content, $matches);
echo '<pre>';
var_dump($matches);
echo '</pre>';
?>
And yes, result is not empty :)

How do I search a file and return an array of the results and line number in PHP?

How do I search a file and return an array of the results so that I can use it in a collection in PHP?
So, for example, say I have a .txt file with something like:
hellohello
hihi
heywhats up
hello hey whats up
hello
And I want to search for all occurrences with hello and its line number, then return it as an array so I can use it in a data collector.
So, it would return the line number and line, like:
$results = array
(
array('1', 'hellohello'),
array('4', 'hello hey whats up'),
array('5', 'hello'),
);
My idea is to us file_get_contents.
So, for example..
$file = 'example.txt';
function get_file($file) {
$file = file_get_contents($file);
return $file;
}
function searchFile($search_str) {
$matches = preg_match('/$search_str/i', get_file($file);
return $matches;
}
As an alternative, you could also use file() function so it reads the entire file into an array. Then you could just loop, then search. Rough example:
$file = 'example.txt';
$search = 'hello';
$results = array();
$contents = file($file);
foreach($contents as $line => $text) {
if(stripos($text, $search) !== false) {
$results[] = array($line+1, $text);
}
}
print_r($results);
Sidenote: stripos() is just an example, you could still use your other way/preference to search the needle for that particular line.

manipulating array to use in different contex

I am using regex to match pattern. Then pushing matched result using pushToResultSet. In both way of doing, would $resultSet have similar array content? Similar means not
insense of value, but format. I want to use 2nd way in alternative to 1st code.
UPDATE: Example with sample input http://ideone.com/lIaP49
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
$this->pushToResultSet($matches);
}
return $resultSet;
Now I am doing this in another way and pushing array in similar way. As $matches is array and here $b is also array, I guess both code are similar
$b = array();
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
foreach ($test as $value)
{
$value = strtolower($value);
// Capture also the numbers so we just concat later, no more string substitution.
$matches = preg_split('/(\d+)/', $value, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if ($matches)
{
$newValue = array();
foreach ($matches as $word)
{
// Replace if a valid word number.
$newValue[] = (isset($arrwords[$word]) ? $arrwords[$word] : $word);
}
$newValue = implode($newValue);
if (preg_match($pattern, $newValue))
{
$b[] = $value;
$this->pushToResultSet($b);
}
}
}
//print_r($b);
return $resultSet;
UPDATE
ACtual code which I want to replace out with 2nd code in the question:
<?php
class Phone extends Filter{
function parse($text, $words)
{
$arrwords = array(0=>'zero',1=>'one',2=>'two',3=>'three',4=>'four',5=>'five',6=>'six',7=>'seven',8=>'eight',9=>'nine');
preg_match_all('/[A-za-z]+/', $text, $matches);
$arr=$matches[0];
foreach($arr as $v)
{
$v = strtolower($v);
if(in_array($v,$arrwords))
{
$text= str_replace($v,array_search($v,$arrwords),$text);
}
}
//$resultSet = array();
$l = strlen($text);
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
//print_r($matches);
}
//print_r($matches);
$this->pushToResultSet($matches);
return $resultSet;
}
}
After running both codes, run PHP's var_dump function on the output variables.
If the printed output matches for your definition of similar array content, then your answer is yes. Otherwise, your answer is no.

Using Regex to find if the string is inside the array and replace it + PHP

$restricted_images = array(
"http://api.tweetmeme.com/imagebutton.gif",
"http://stats.wordpress.com",
"http://entrepreneur.com.feedsportal.com/",
"http://feedads.g.doubleclick.net"
);
This are the list of images that I want to know if a certain string has that kind of string.
For example:
$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/".
Since "http://api.tweetmeme.com/imagebutton.gif" is in the $restricted_images array and it is also a string inside the variable $string, it will replace the $string variable into just a word "replace".
Do you have any idea how to do that one? I'm not a master of RegEx, so any help would be greatly appreciated and rewarded!
Thanks!
why regex?
$restricted_images = array(
"http://api.tweetmeme.com/imagebutton.gif",
"http://stats.wordpress.com",
"http://entrepreneur.com.feedsportal.com/",
"http://feedads.g.doubleclick.net"
);
$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
$restrict = false;
foreach($restricted_images as $restricted_image){
if(strpos($string,$restricted_image)>-1){
$restrict = true;
break;
}
}
if($restrict) $string = "replace";
maybe this can help
foreach ($restricted_images as $key => $value) {
if (strpos($string, $value) >= 0){
$string = 'replace';
}
}
You don't really need regex because you're looking for direct string matches.
You can try this:
foreach ($restricted_images as $url) // Iterate through each restricted URL.
{
if (strpos($string, $url) !== false) // See if the restricted URL substring exists in the string you're trying to check.
{
$string = 'replace'; // Reset the value of variable $string.
}
}
You don't have to use regex'es for this.
$test = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
foreach($restricted_images as $restricted) {
if (substr_count($test, $restricted)) {
$test = 'FORBIDDEN';
}
}
// Prepare the $restricted_images array for use by preg_replace()
$func = function($value)
{
return '/'.preg_quote($value).'/';
}
$restricted_images = array_map($func, $restricted_images);
$string = preg_replace($restricted_images, 'replace', $string);
Edit:
If you decide that you don't need to use regular expressions (which is not really needed with your example), here's a better example then all of those foreach() answers:
$string = str_replace($restricted_images, 'replace', $string);

Categories