Search for a specific string within another string with PHP - php

I need to search a string for any occurances of another string in PHP. I have some code that I've been playing with, but it doesn't seem to be working.
Here is my code:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos == false) {
echo "allow";
exit;
} else {
echo "deny";
exit;
}
}
I have tried some of the options below, but it still does not find the match. Here is what I'm searching:
I need to find:*
blah
In:
http://blah.com
Nothing seems to find it. The code works in regular sentences:
Today, the weather was very nice.
It will find any word from the sentence, but when it is all together (in a URL) it can't seem to find it.

When checking for boolean FALSE in php, you need to use the === operator. Otherwise, when a string match is found at the 0 index position of a string, your if condition will incorrectly evaluate to true. This is mentioned explicitly in a big red box in the php docs for strpos().
Also, based on a comment you left under another answer, it appears as though you need to remove the exit statement from the block that allows access.
Putting it all together, I imagine your code should look like this:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos === false) { // use === instead of ==
echo "allow";
} else {
echo "deny";
exit;
}
}
Update:
With the new information you've provided, I've rewritten the logic:
function isAllowed($location) {
$keywords = array('blah', 'another-restricted-word', 'yet-another-restricted-word');
foreach($keywords as $keyword) {
if (strpos($location, $keyword) !== FALSE) {
return false;
}
}
return true;
}
$location = 'http://blah.com/';
echo isAllowed($location) ? 'allow' : 'deny';

Related

PHP's strpos() not working and always getting into the if condition

I'm trying to check if a specific character is not present in a string in my code and apparently php doesn't care about anything and always gets inside the if
foreach($inserted as $letter)
{
if(strpos($word, $letter) !== true) //if $letter not in $word
{
echo "$word , $letter, ";
$lives--;
}
}
In this case $word is "abc" and $letter is "b", I've tried changing a lot of random things like from true to false and things like that but I can't get it, can anyone help me please?
Changing the way you validate should fix it, like below:
foreach($inserted as $letter)
{
//strpos returns false if the needle wasn't found
if(strpos($word, $letter) === false)
{
echo "$word , $letter, ";
$lives--;
}
}
if(strpos($word, $letter) === false) //if $letter not in $word
{
echo "$word , $letter, ";
$lives--;
}
also, be careful to check explicitly against false, strpos can return 0 (a falsey value) if the match is in the 0th index of the string...
for example
if (!strpos('word', 'w') {
echo 'w is not in word';
}
would output the, possibly confusing, message 'w is not in word'

List all elements in array containing certain word in PHP

I'm attempting to make a search feature for my website using PHP. Right now, I have this code to create an array of all files in a directory, which works just fine, but I've hit a snag with my next step. I want it to now list all elements in that array that contain a certain word (the users search), this way I can do something with them later in HTML. My idea was to make a loop that runs strpos for each element and list only the ones it finds matches for. I've tried that, but it always gave me nothing. This is my honest attempt:
<?php
$search = "Pitfall";
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename)
{
if ($filename->isDir()) continue;
foreach ($filename as &$result)
{
$pos = strpos($result, $search);
if ($pos === true) {
echo "$result\n";
}
}
}
?>
Thank you for any help
I think your issue is with your conditional:
if ($pos === true)
strpos() does not return true. It returns the position of the string or false. See docs. You could instead use:
if ($pos !== false)
Edited:
The RecusiveIteratorIterator does not return a string. It returns an object. Here I am typecasting the object so that it gets the correct filename. From there, you don't need to iterate over again, as this is just a string at this point.
$search = "wp-config";
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename)
{
$filename = (string) $filename;
if (is_dir($filename)) continue;
$pos = strpos($filename, $search);
if ($pos !== false) {
echo "$filename <br />";
}
}

Check whether the given two words are existing in a PHP string

I want to check if a string contains two specific words.
For example:
I need to check if the string contains "MAN" & "WAN" in a sentence like "MAN live in WAN" and returns true else false.
What I've tried is looping string function in a conditional way:-
<?php
$data = array("MAN","WAN");
$checkExists = $this->checkInSentence($data);
function checkInSentence( $data ){
$response = TRUE;
foreach ($data as $value) {
if (strpos($string, $word) === FALSE) {
return FALSE;
}
}
return $response;
}
?>
Is it the right method or do I've to change it? How to implement this any suggestions or idea will be highly appreciated.
Note: data array may contain more than two words may be. I just need check whether a set of words are exists in a paragraph or sentence.
Thanks in advance !
It's alsmost good. You need to make it set the response to false if a word is not included. Right now it'll always give true.
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
Try this:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
This also should work!
$count = count($data);
$i = 0;
foreach ($data as $value) {
if (strpos($string, $value) === FALSE) {
#$response = TRUE; // This is subject to change so not reliable
$i++;
}
}
if($i<$data)
response = FALSE;

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

Matching a Pattern in PHP

I am trying to validate whether or not a string contains and starts with BA700. I have tried using the preg_match() function in PHP but I have not had any luck. My code is below:
preg_match('/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/', $search))
This does not work unfortunately. Any ideas?
UPDATES CODE:
$needle = 'BA700';
$haystack = 'BA70012345';
if (stripos($haystack, $needle)) {
echo 'Found!';
}
This does not work for me either
Here is how to correctly use stripos
if (stripos($haystack, $needle) !== false) {
echo 'Found!';
}
Maybe I am taking this a little too literally, but:
if (strncmp($string, 'BA700', 5) === 0) {
// Contains and begins with 'BA700'
}
If the BA700 is case-insensitive then:
if (strncasecmp($string, 'ba700', 5) === 0) {
// Contains and begins with 'ba700'
}
There should not be much more to it than that.
The regular expression, in case you want to know, is:
if (preg_match('/^BA700/', $string) === 1) {
// Contains and begins with 'ba700'
}
Try with substr like
$needle = 'BA700';
$haystack = 'BA70012345';
if(substr($haystack, 0, 4) == $needle) {
echo "Valid";
} else {
echo "In Valid";
}
You can also check regards with the case by changing both of them in either UPPER or LOWER like
if(strtoupper(substr($haystack, 0, 4)) == $needle) {
echo "Valid";
} else {
echo "In Valid";
}

Categories