Finding a substring within a PHP array? - php

I have a PHP script that loops through each row of a CSV file and organizes each line into an array:
$counter = 0;
$file = file($ReturnFile);
foreach($file as $k){
if(preg_match('/"/', $k)==1){
$csv[] = explode(',', $k);
$counter++;
}
}
...
while($x<$counter){
$line=$csv[$x];
This works; my question is about how to find a substring within each line. This:
foreach($line as $value){
if($value==$name_search){
// action
works if the value of $line is exactly equal to the value of $name_search ($name_search is a person's last name). However, this doesn't work if there is a space or additional characters in the value of $line (for example: $line equal to "Wilson (ID: 345)" or "Wilson " won't match a $name_search value of "Wilson".
So far I've tried:
if(strpos($value, $res_name_search) !== false){
if(substr($value, 0, strrpos($value, ' '))==$res_name_search){
if(substr(strval($value), 0, strrpos(strval($value), ' '))==$res_name_search){
without success ... Do I have a syntax error and/or is there a better way to accomplish this?

I think you have inverted the parameters. The following should work:
if (strpos($res_name_search, $value) !== false)
A minor note: use stripos for case-insensitive search.

Try to use strpos like this: if (strpos($res_name_search, $value))

use php TRIM function
Convert to either of the lowercase or uppercase before compairing
use var_dump to check the data type
instead of using var_dump type cast $value and $name_search to STRING
also check ===
Remove spaces (if required)
Use regular expression to remove (, ), :, -, ; etc...
and of course apply function strpos
You can apply above mentioned points in your logic (Order of points may be different)

Try this:
$str = 'This is my test: wilson ';
$search = "wilson";
if(strpos(strtolower($str), strtolower($search)) !== false){
echo 'found it';
}

You can also try this:
if (preg_match('/'.strtolower($res_name_search).'/', strtolower($value)))

This is the sort of situations for which the built-in PHP function stristr exists. This function is the case-insensitive equivalent of the strstr function which, according to the docs:
Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.
Using this function, achieving such a task becomes as easy as:
foreach($line as $value){
if( stristr($value, $name_search) !== FALSE){
// substring was found in search string, perform your action
You can read more about it in the official documentation
I hope this helps.

I advice you to use fgetcsv function, this will return you an array of your columns for each iteration as follow :
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// ...
}
If in your CSV file, the column NAME is in position 2 for example and you want to know if token exist, just use
if (strpos('Wilson', $data[2] !== FALSE) {
// do your job
}
if you want to deal with case-insentivie, use stripos function

Related

how to use php to check if a variable contains a group of characters

i have a variable and i want to use php to check if it contains a group of characters
i would like the code to be like this
$groupofcharacters = ["$","#","*","("];
if($variable contains any of the letters in $groupofcharacters){
//do something}
i know that this will need the use of strpos() function but how can i use the strpos function to check if a variable contains a group of characters without me having to create a strpos() function for all the characters that i want to check for.
please if you don't understand you can tell me in the comments
Best way to solve your issue is by using RegEx. Try this:
<?php
$variable = 'Any string containing $*(#';
$sPattern = '/[$#*(]/';
if (preg_match($sPattern, $variable)) {
// Do something
}
You can use strpbrk to achieve this. The doc says:
strpbrk — Search a string for any of a set of characters
Returns a string starting from the character found, or FALSE if it is not found.
Snippet:
<?php
if(strpbrk($variable,"$#*(") !== false){
// your logic goes here
}
check if it has any char. Using strpos
First you need to combine the array as string after check ot if there's one of them in the
$groupofcharacters = ["$","#","*","("];
$strs = implode("", $groupofcharacters);
foreach(str_split($variable) as $s) {
if (strpos($s, $strs)) {
echo "it contains "; continue;
}
}

Warning: stripos() expects at least 2 parameters in php

I wrote a simple function in php and passing arguments to uppercase the letters based on passing array index value but I'm getting this error
Warning: stripos() expects at least 2 parameters
what I'm doing wrong can anyone suggest me.
i'm newbie to php just starts learning.
<?php
function doCapital($string, $array)
{
$stringArray = explode(",", $string);
for( $i=0; $i<count($stringArray); $i++)
{
if(stripos($stringArray)>-1){
$stringArray[$i] = $stringArray[$i].ucfirst();
echo $stringArray[$i];
}
}
return implode(" ",$stringArray);
}
echo doCapital('abcd', [1,2]);
Apologies, on re-reading my last answer I realise that it did seem very unfriendly - I bashed out a quick answer and didn't read it back. What I was trying to say is that with errors like this the quickest solutions to go to the php manual and check the required parameters - which in this case is a needle and a haystack (i.e something to search, and something to search in).
You will likely find the same error here
$stringArray[$i] = $stringArray[$i].ucfirst(); as ucfirst requires a string to be passed - here you're using it like jQuery so php thinks you are trying to concatenate a string, it should say ucfirst($stringArray[$i])
you also can't explode with a comma unless your string contains them, so in the example you have you would receive the same string back, I think you mean to use something like str_split
also I would reiterate that I think you need to use in_array for what you're trying to achieve, like this:
function doCapital($string, $array)
{
$stringArray = str_split($string);
foreach($stringArray as $key => $value)
{
//see if the key exists in the array of characters to change the case for
//and update if it does
if(in_array($key,$array)){
$stringArray[$key] = ucfirst($value);//thinking about it I might just use strtoupper since there's only one letter anyway - I'm not sure that there's any real performance benefit either way
}
}
return implode("",$stringArray);
}
echo doCapital('abcd', [1,2]); //outputs aBCd
stripos - Find the position of the first occurrence of a case-insensitive substring in a string
You are missing the second parameter, The correct syntax to use the function stripos is
stripos ($haystack ,$needle);
Here
$haystack -> The string in which you are searching
$needle -> The substring
For example :
$findme = 'x';
$mystring1 = 'xyz';
$pos1 = stripos($mystring1, $findme);
if ($pos1 !== false) {
echo "We found '$findme' in '$mystring1' at position $pos1";
}

PHP compare two text files by lines

I need to compare two language files - English and German. Each text file has one word/phrase per line. Word/phrase [x] in first language is word/phrase [x] in second language. The translated word is on the same line in the second file.
I tried to get the translation using the following code, but it seems that the loop does not work. I always get "none". Any ideas?
function translation($word,$service,$sprache1,$sprache2){
$typus ="transl";
$mypath = "data/".$service."/";
mkdir($mypath,0777,TRUE);
//fh - First language file
$myFile = $mypath."".$typus."-".$sprache1.".txt";
$fh = file($myFile) or die("can't open file");
//fh2 - Second language file
$myFile2 = $mypath."".$typus."-".$sprache2.".txt";
$fh2 = file($myFile2) or die("can't open file");
$x=0;
$result = "none";
foreach ($fh as $line) {
if (stripos($word,$line))
{$result = $fh2[$x];
break;
}
$x=$x+1;
}
return $result;
}
I think your problem is in wrong if statement.
The point is that stripos (like strpos) can return 0 or false as a result.
For example if you search for 'cat' in a word 'cats' stripos will return 0, as it's the first position of cat-string.
On the other side, if you search 'dog' in a word 'cats' stripos will return false as nothing is found.
So in you function the if case should be more strict:
if (stripos($word,$line) !== false)
This means that your word is found even if it starts from position 0.
You current if statement doesn't allow 0 (zero) value to be accepted.
After testing your code I found 2 different problems.
First of all, be careful with stripos. This function returns 0 if the $needle is found at the beginning (i.e. position 0), and false if the $needle was not found. In PHP, 0 is eval'd to false by default.
You should change your if statement to:
if(stripos($word, $line) !== false)
Note the !== operator, which is stronger than !=.
The second and most important problem, which prevents your function from working, is that you compare lines which can contains invisible characters (e.g. "newline" chars). You should trim the strings before comparing them.
I'd change your if statement for:
if(trim($word) === trim($line))
which is simpler. Or if you really want to keep stripos:
if(stripos(trim($word), trim($line)) !== false)

Check if any value in an array exists within a haystack string

I have a string like abcdefg123hijklm. I also have an array which contains several strings like [456, 123, 789].
I want to check if the number in the middle of abcdefg123hijklm exists in the array.
How can I do that? I guess in_array() won't work.
So you want to check if any substring of that particular string (lets call it $searchstring) is in the array?
If so you will need to iterate over the array and check for the substring:
foreach($array as $string)
{
if(strpos($searchstring, $string) !== false)
{
echo 'yes its in here';
break;
}
}
See: http://php.net/manual/en/function.strpos.php
If you want to check if a particular part of the String is in the array you will need to use substr() to separate that part of the string and then use in_array() to find it.
http://php.net/manual/en/function.substr.php
Another option would be to use regular expressions and implode, like so:
if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
echo("Yes, the string '{$matches[0]}' was found in the search string.");
else
echo("None of the strings in the array were found in the search string.");
It's a bit less code, and I would expect it to be more efficient for large search strings or arrays, since the search string will only have to be parsed once, rather than once for every element of the array. (Although you do add the overhead of the implode.)
The one downside is that it doesn't return the array index of the matching string, so the loop might be a better option if you need that. However, you could also find it with the code above followed by
$match_index = array_search($matches[0], $array);
Edit: Note that this assumes you know your strings aren't going to contain regular expression special characters. For purely alphanumeric strings like your examples that will be true, but if you're going to have more complex strings you would have to escape them first. In that case the other solution using a loop would probably be simpler.
You can do it reversely. Assume your string is $string and array is $array.
foreach ($array as $value)
{
// strpos can return 0 as a first matched position, 0 == false but !== false
if (strpos($string, $value) !== false)
{
echo 'Matched value is ' . $value;
}
}
Use this to get your numbers
$re = "/(\d+)/";
$str = "abcdefg123hijklm";
preg_match($re, $str, $matches);
and ( 123 can be $matches[1] from above ):
preg_grep('/123/', $array);
http://www.php.net/manual/en/function.preg-grep.php

How to get a line in a Text file using cakephp

So I know how to open a file in php is done using
fopen("file.txt", 'r') ;
but i want to get one line in the file and so some string manipulation on it.
such as " Serving this with <0101010> "
I want to find the line that starts with "Serving this" and take the whole line add it to $line
Then i will get remove the <> and add it to $number , and same for <0101010>
names of methods that can be used would be just perfect
Okay, the simple method you probably want to use is:
foreach (file("file.txt") as $line) {
if (strpos($line, "Serving this with") === 0) {
print "found";
The file function is easier than fopen/fread, as it returns a list of lines already. And the strpos function simply searches the string and returns the position. It must be checked with === 0 here, because it could also return false.
Instead of printing "found" you want to extract something, so you must again use strpos to find your delimeters < and > and then extract the part with substr:
$l = strpos($line, "<"); // well, actually needs more logic,
$r = strpos($line, ">"); // some if tests, if both are true
$wanthave = substr($line, $l, $r - $l + 1);
A simpler option I would use are regular expressions. And the regex itself looks simple enough in your case:
preg_match_all('/^Serving this with <(\d+)>/m',
file_get_contens("file.txt"),
$matches);
print_r($matches[1]);
you can also use fgets() read file line by line.
$line = fgets($file_handle);

Categories