No success by using strpos when searching a string - php

I have the following code/string:
$ids="#222#,#333#,#555#";
When I'm searching for a part using:
if(strpos($ids,"#222#"))
it won't find it. But when I'm searching without the hashes, it works using:
if(strpos($ids,"222"))
I've already tried using strval for the search parameter, but this won't work also.

strpos starts counting from 0, and returns false if nothing is found. You need to check if it's false with === like this...
if (strpos($ids, '#222#') === false) // not found
Or use !== if you want the opposite test...
if (strpos($ids, '#222#') !== false) // found
See the PHP Manual entry for more information

You are not explecitely testing for FALSE when using strpos. Use it like this:
if(strpos($string, '#222#') !== FALSE) {
// found
} else {
// not found
}
Explanation: You are using it like this:
if(strpos($string, '#222#')) {
// found
}
What is the problem with this? Answer: strpos() will return the position in string where the substring was found. In you case 0 as its at the beginning of the string. But 0 will be treated as false by PHP unless you issue an explicit check with === or !==.

It is working as expected. strpos() returns 0 because the string you're searching for is at the beginning of the word. You need to do an equality search:
Update your if() statement as follows:
if(strpos($ids, '#222') !== false)
{
// string was found!
}

Try with this :
$ids="#222#,#333#,#555#";
if(strpos($ids,"#222#") !== false)
{
echo "found";
}
You should use !== because the position of '#222#' is the 0th (first) character.

Related

Finding a substring within a PHP array?

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

Pick up an url within a string

Hi all I am trying a quick and dirty solution for stopping a comment spammer on my site, trying to pick up this url "https://www.change.org/en-GB/petitions/rockstar-games-release-pc-games-for-the-linux-operating-system" in a bunch of text like so:
if (strpos($_POST['text'], "https://www.change.org/en-GB/petitions/rockstar-games-release-games-for-linux") == true)
{
header("Location: /home/banned");
}
Sadly that doesn't seem to work, is there a good way to do it?
from php
strpos()
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
it wont return TRUE so do it like !==FALSE
You should use !== false instead of == true
if (strpos($_POST['text'], "https://www.change.org/en-GB/petitions/rockstar-games-release-games-for-linux") !== false)
{
header("Location: /home/banned");
exit;
}
strpos returns "Returns the position of where the needle exists" or "Returns FALSE if the needle was not found.". Thus, you should test whether not not it returns false:
if (strpos(...) === false) {
// needle was not found
}
In your case you need to check for the negation (i.e. needle was found):
if (strpos($_POST['text'], "https://...") !== false) {
header("Location: /home/banned");
}
Note the extract equals sign in the both operators (=== and !==), which is there to make comparison type strict. If you don't use type strict comparison and needle is found at position 0, you get a false negative result (0 is interpreted to be equal to false).

Check if a string contain multiple specific words

How to check, if a string contain multiple specific words?
I can check single words using following code:
$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad') !== false) {
echo 'true';
}
But, I want to add more words to check. Something like this:
$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad || naughty') !== false) {
echo 'true';
}
(if any of these words is found then it should return true)
But, above code does not work correctly. Any idea, what I'm doing wrong?
For this, you will need Regular Expressions and the preg_match function.
Something like:
if(preg_match('(bad|naughty)', $data) === 1) { }
The reason your attempt didn't work
Regular Expressions are parsed by the PHP regex engine. The problem with your syntax is that you used the || operator. This is not a regex operator, so it is counted as part of the string.
As correctly stated above, if it's counted as part of the string you're looking to match: 'bad || naughty' as a string, rather than an expression!
You can't do something like this:
if (strpos($data, 'bad || naughty') !== false) {
instead, you can use regex:
if(preg_match("/(bad|naughty|other)/i", $data)){
//one of these string found
}
strpos does search the exact string you pass as second parameter. If you want to check for multiple words you have to resort to different tools
regular expressions
if(preg_match("/\b(bad|naughty)\b/", $data)){
echo "Found";
}
(preg_match return 1 if there is a match in the string, 0 otherwise).
multiple str_pos calls
if (strpos($data, 'bad')!==false or strpos($data, 'naughty')!== false) {
echo "Found";
}
explode
if (count(array_intersect(explode(' ', $data),array('bad','naugthy')))) {
echo "Found";
}
The preferred solution, to me, should be the first. It is clear, maybe not so efficient due to the regex use but it does not report false positives and, for example, it will not trigger the echo if the string contains the word badmington
The regular expression can become a burden to create if it a lot of words (nothing you cannot solve with a line of php though $regex = '/\b('.join('|', $badWords).')\b/';
The second one is straight forward but can't differentiate bad from badmington.
The third split the string in words if they are separated by a space, a tab char will ruins your results.
if(preg_match('[bad|naughty]', $data) === true) { }
The above is not quite correct.
"preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred."
So it should be just:
if(preg_match('[bad|naughty]', $data)) { }
substr_count()
I want to add one more way doing it with substr_count() (above all other answers):
if (substr_count($data, 'bad') || substr_count($data, 'naughty')){
echo "Found";
}
substr_count() is counting for how many times the string appears, so when it's 0 then you know that it was not found.
I would say this way is more readable than using str_pos() (which was mentioned in one of the answers) :
if (strpos($data, 'bad')!==false || strpos($data, 'naughty')!== false) {
echo "Found";
}
You have to strpos each word. Now you are checking if there is a string that states
'bad || naughty'
which doesn't exist.
A simple solution using an array for the words to be tested and the array_reduce() function:
$words_in_data = array_reduce( array( 'bad', 'naughty' ), function ( $carry, $check ) use ( $data ) {
return ! $carry ? false !== strpos( $data, $check ) : $carry;
} );
Then you can simply use:
if( $words_in_data ){
echo 'true';
}
Here is a function that can perform this operation without using regular expressions which could be slower. Instead of passing a single string for the task, pass an array like
if (strposMultiple($data, ['bad', 'naughty']) !== false) {
//...
}
Here is the function:
function strposMultiple($haystack, $needle, $offset = 0) {
if(is_string($needle))
return strpos($haystack, $needle, $offset);
else {
$min = false;
foreach($needle as $n) {
$pos = strpos($haystack, $n, $offset);
if($min === false || $pos < $min) {
$min = $pos;
}
}
return $min;
}
}

If string contains forward slash

How do i make a if statement which checks if the string contains a forward slash?
$string = "Test/Test";
if($string .......)
{
mysql_query("");
}
else
{
echo "the value contains a invalid character";
}
You can use strpos, which will make sure there is a forward slash in the string but you need to run it through an equation to make sure it's not false. Here you can use strstr(). Its short and simple code, and gets the job done!
if(strstr($string, '/')){
//....
}
For those who live and die by the manual, when the haystack is very large, or the needle is very small, it is quicker to use strstr(), despite what the manual says.
Example:
Using strpos(): 0.00043487548828125
Using strstr(): 0.00023317337036133
if(strpos($string, '/') !== false) {
// string contains /
}
From the PHP manual of strstr:
Note:
If you only want to determine if a particular needle occurs within
haystack, use the faster and less memory intensive function strpos()
instead.
Use strpos()
If it doesn't return false, the character was matched.
I compared strpos() results with 0. Somehow comparison with false did not work for me.
if (strpos($t, '/') !== 0) {
echo "No forward slash!";
}

Check if a string does not contains a specific substring [duplicate]

This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 26 days ago.
In SQL we have NOT LIKE %string%
I need to do this in PHP.
if ($string NOT LIKE %word%) { do something }
I think that can be done with strpos()
But can’t figure out how…
I need exactly that comparission sentence in valid PHP.
if ($string NOT LIKE %word%) { do something }
if (strpos($string, $word) === FALSE) {
... not found ...
}
Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.
Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.
Use strpos. If the string is not found it returns false, otherwise something that is not false. Be sure to use a type-safe comparison (===) as 0 may be returned and it is a falsy value:
if (strpos($string, $substring) === false) {
// substring is not found in string
}
if (strpos($string, $substring2) !== false) {
// substring2 is found in string
}
use
if(stripos($str,'job')){
// do your work
}
<?php
// Use this function and Pass Mixed string and what you want to search in mixed string.
// For Example :
$mixedStr = "hello world. This is john duvey";
$searchStr= "john";
if(strpos($mixedStr,$searchStr)) {
echo "Your string here";
}else {
echo "String not here";
}
Kind of depends on your data, doesn't it? strpos('a foolish idea','fool') will show a match, but may not be what you want. If dealing with words, perhaps
preg_match("!\b$word\b!i",$sentence)
is wiser. Just a thought.

Categories