strpos with two words to find - php

I found this example on stackoverflow:
if (strpos($a,'are') !== false) {
echo 'true';
}
But how do I make it search for two words. I need something like this: if $a contains the words "are" or "be" or both echo "contains";
I tried xor and ||

Just check both words separately and use the boolean or-operator to check if either one or both are contained in $a:
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo "contains";
}
Note that due to the or-operator, the second check (for 'be') is not performed if the first one already showed that $a contains 'are'.

An alternative: Searches any length of words in the longer string.
Since you've haven't picked an answer from all the strpos answers (most of which should work with just two words, try this function of mine which exceeds word limits. It can find any varying length of words from the longer string (but doesn't use strpos). I think with strpos, you would have to know the number of words to determine how many || you should use or make use of a loop (sort of). This method eliminates all that and gives you a more flexible way to reuse your codes. I thinks codes should be flexible, reusable and dynamic. Test it and see if it does what you want!
function findwords($words, $search) {
$words_array = explode(" ", trim($words));
//$word_length = count($words_array);
$search_array = explode(" ", $search);
$search_length = count($search_array);
$mix_array = array_intersect($words_array, $search_array);
$mix_length = count($mix_array);
if ($mix_length == $search_length) {
return true;
} else {
return false;
}
}
//Usage and Examples
$words = "This is a long string";
$search = "is a";
findwords($words, $search);
// $search = "is a"; // returns true
// $search = "is long at"; // returns false
// $search = "long"; // returns true
// $search = "longer"; // returns false
// $search = "is long a"; // returns true
// $search = "this string"; // returns false - case sensitive
// $search = "This string"; // returns true - case sensitive
// $search = "This is a long string"; // returns true

$a = 'how are be';
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo 'contains';
}

Try:
if (strpos($a,'are') !== false || strpos($a,'be') !== false)
echo 'what you want';

if ((strpos($a,'are') !== false) || (strpos($a, 'be') !==false) {
echo 'contains';
}

Is this what you want?
if ((strpos($a,'are') !== false) || (strpos($a,'be') !== false)) {
echo 'contains';
}

if (strpos($a,'are') !== false || strpost($a, 'be') !== false) {
echo "contains";
}
Brain Candy:
If the first one returns true, it'll skip the second check. So both can be true. If the first one is false, ONLY then will it check the second. This is called a short circuit.

if(strstr($a,'are') || strstr($a,'be')) echo 'contains';
Hum, like this?

if (strpos($a,'are') || strpos($a, 'be') {
echo 'contains';
}

Related

php - check if value is in csv-file

im trying to check if two php-values are in one line in the csv fiel.
csv:
password, name
12345, max
44444, emil
but when my variable is $password="123" and in the csv file its "12345" he accepts it.
But, how can i check if its 100% equals? I dont understand why "123" is enough?
$search = $name;
$search2 = $password;
$lines = file('Benutzer.csv');
$line_number = false;
$line_number2 = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE );
$line_number2 = (strpos($line, $search2) !== FALSE );
}
if($line_number and $line_number2 ){
header('Location: alert_anmelden_erfolgreich.php');
}
else{
header('Location: alert_anmelden_NICHT_erfolgreich.php');
}
strpos looks for a substring in a string. So first things first"
strpos('12345','345')
will return 2 since the substring exists starting at that index. In your case:
strpos('12345','123')
or really 1,12,123,1234,12345 will all return the position 0. Now, when equating as you do to false you're essentially getting:
0==`false`
which is of course true because 0 an be casted to false. As #u_mulder, commented use of the full type equality operator === would fix that, but still won't solve your problem!. What you want is strcmp, which will return 0(false) only if the strings are identical, and can be used like you wanted. You could also use === or == between the strings since you don't care about 'less/more' string.
if( $line === $search )

Find if a value exist in a CSV file with PHP

This is my code to check if a row of my .csv file contains a specific name, but it does not work.
I think it has something to do with the if statement.
$file_handle = fopen("sources.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] = 'paul') {
echo 'Found';
}
}
fclose($file_handle);
I am trying to check in sources.csv files, for the name 'Paul' .
I can't use a database like MySQL for technical reasons.
Since you haven't provided a sample of your file, am submitting the following as an alternative.
Do note that in your present code, you are assigning using a single equal sign = instead of comparing using == or ===, just saying as an FYI.
if ($line_of_text[0] = 'paul') should read as if ($line_of_text[0] == 'paul')
Assuming the following .csv format (will work even without the commas) and is case-sensitive, consult Footnotes regarding case-insensitive search.
Paul, Larry, Robert
Code:
<?php
$search = "Paul";
$lines = file('sources.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE);
}
if($line_number){
echo "Results found for " .$search;
}
else{
echo "No results found for $search";
}
Footnotes:
For a case-insensitive search, use stripos()
$line_number = (stripos($line, $search) !== FALSE);
Row number found on...
To give you the row's number where it was found:
$line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
or (case-insensitive)
$line_number = (stripos($line, $search) !== FALSE) ? $count : $line_number;
then just echo $line_number;
Your problem is this line:
if ($line_of_text[0] = 'paul') {
This will always be true because you are assigning the value paul to $line_of_text[0] with the assign operator =. What you want to do is check if the two are equal, so you need to use the equality operator, ==. The line of code should be:
if ($line_of_text[0] == 'paul') {
There is also the === equality operator in PHP which checks for the same value AND same type. (This is a particularly nasty feature of PHP when compared to compiled languages)
e.g. consider: `$foo = 5; $bar = "5";
if ($foo === $bar) // this will be false because foo is an int, and bar is a string
if ($foo == $bar) // this will be true
Don't be confused with the != comparison operator:
if ($foo != $bar) // foo is not equal to bar (note the single =)
Try using in_array instead of ==
if(in_array('paul', $line_of_text)) {
// FOUND
}

Check if string contains one of several words

I am trying to make a word filter in php, and I have come across a previous Stackoverlow post that mentions the following to check to see if a string contains certain words. What I want to do is adapt this so that it checks for various different words in one go, without having to repeat the code over and over.
$a = 'How are you ?';
if (strpos($a,'are') !== false) {
echo 'true';
}
Will it work if I mod the code to the following ?......
$a = 'How are you ?';
if (strpos($a,'are' OR $a,'you' OR $a,'How') !== false) {
echo 'true';
}
What is the correct way of adding more than one word to check for ?.
To extend your current code you could use an array of target words to search for, and use a loop:
$a = 'How are you ?';
$targets = array('How', 'are');
foreach($targets as $t)
{
if (strpos($a,$t) !== false) {
echo 'one of the targets was found';
break;
}
}
Keep in mind that the use of strpos() in this way means that partial word matches can be found. For example if the target was ample in the string here is an example then a match will be found even though by definition the word ample isn't present.
For a whole word match, there is an example in the preg_match() documentation that can be expanded by adding a loop for multiple targets:
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $a)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
}
Read it somewhere:
if(preg_match('[word1|word2]', $a)) { }
if (strpos($ro1['title'], $search)!==false or strpos($ro1['description'], $search)!== false or strpos($udetails['user_username'], $search)!== false)
{
//excute ur code
}
If you have a fixed number of words, which is not too big you can easily make it like this:
$a = 'How are you ?';
if (strpos($a,'are') !== false || strpos($a,'you') !== false || strpos($a,'How') !== false) {
echo 'true';
}
I built methods using both str_contains and preg_match to compare speeds.
public static function containsMulti(?string $haystackStr, array $needlesArr): bool
{
if ($haystackStr && $needlesArr) {
foreach ($needlesArr as $needleStr) {
if (str_contains($haystackStr, $needleStr)) {
return true;
}
}
}
return false;
}
preg_match is always a lot slower (2-10 times slower, depending on several factors), but could be useful if you want to extend it for whole-word matching, etc.
public static function containsMulti(?string $haystackStr, array $needlesArr): bool
{
if ($haystackStr && $needlesArr) {
$needlesRegexStr = implode('|', array_map('preg_quote', $needlesArr));
return (bool) preg_match('/(' . $needlesRegexStr . ')/', $haystackStr);
}
return false;
}
If you need a multibyte-save version. try this
/**
* Determine if a given string contains a given substring.
*
* #param string $haystack
* #param string|string[] $needles
* #param bool $ignoreCase
* #return bool
*/
public static function contains($haystack, $needles, $ignoreCase = false)
{
if($ignoreCase){
$haystack= mb_strtolower($haystack);
$needles = array_map('mb_strtolower',$needles);
}
foreach ((array) $needles as $needle) {
if ($needle !== '' && mb_strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}

How to check if a string contains a specific text [duplicate]

This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 9 years ago.
<?php
$a = '';
if($a exist 'some text')
echo 'text';
?>
Suppose I have the code above, how to write the statement if($a exist 'some text')?
Use the strpos function: http://php.net/manual/en/function.strpos.php
$haystack = "foo bar baz";
$needle = "bar";
if( strpos( $haystack, $needle ) !== false) {
echo "\"bar\" exists in the haystack variable";
}
In your case:
if( strpos( $a, 'some text' ) !== false ) echo 'text';
Note that my use of the !== operator (instead of != false or == true or even just if( strpos( ... ) ) {) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos.
As of PHP 8.0.0 you can now use str_contains
<?php
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always
return true";
}
Empty strings are falsey, so you can just write:
if ($a) {
echo 'text';
}
Although if you're asking if a particular substring exists in that string, you can use strpos() to do that:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?
if(strpos( $a , 'some text' ) !== false)
If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where 'word' is the word you are searching in the string.
if (strpos($a,'word') !== false) {
echo 'true';
}
or use the is_string method. Whichs returns true or false on the given variable.
<?php
$a = '';
is_string($a);
?>
You can use strpos() or stripos() to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.
Use the operators === or `!== to differ FALSE from 0 in PHP.
You can use the == comparison operator to check if the variable is equal to the text:
if( $a == 'some text') {
...
You can also use strpos function to return the first occurrence of a string:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
See documentation

how can I do a string check inside a string in php?

Does anyone know how can I do a string check inside a string?
for example:
$variable = "Pensioner (other)";
If I want to check whether $variable contain the word 'Pensioner', how can I do it in PHP? I have tried the following code in php, but it's always return me false :(
$pos = strripos($variable,"Pensioner");
if($pos) echo "found one";
else echo "not found";
In the manual, the example uses a === for comparison. The === operator also compares the type of both operands. To check for 'not equal', use !==.
Your search target 'Pensioner' is at position 0, and the function returns 0, which equal false, hence if ($pos) failed all the time. To correct that, your code should read:
$pos = strripos($variable,"Pensioner");
if($pos !== false) echo "found one";
else echo "not found";
Update:
You are using the reverse function strripos, you need to use stripos.
if (stripos($variable, "Pensioner") !== FALSE){
// found
}
else{
// not found
}
This should do:
if (strripos($variable, "Pensioner") !== FALSE){
// found
}
else{
// not found
}
The strict type comparison (!==) is important there when using strpos/stripos.
The problem with strripos and its siblings is that they return the position of the substring found. So if the substring you're searching happens to be at the start, it returns 0 which in a boolean test is false.
Use:
if ( $pos !== FALSE ) ...
$variable = 'Pensioner (other)';
$pos = strripos($variable, 'pensioner');
if ($pos !== FALSE) {
echo 'found one';
} else {
echo 'not found';
}
^ Works for me. Note that strripos() is case insensitive. If you wanted it to be a case-sensitive search, use strrpos() instead.

Categories