Let's say that I have:
$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "that";
How will I check if $strPar contains $strFindMe?
Fastest way is to use strpos:
$exists = strpos($strPar, $strFindMe);
if ($exists !== false) {
// substring is in the main string
}
try something like this
if (false !== strpos($strPar, $strFindMe ) )
$string = "This is a strpos() test";
$pos = strpos($string, "i", 3);
if ($pos === false) {
print "Not found\n";
}else{
print "Found at $pos!\n";
}
<?php
$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "that";
$pos = strpos($strPar, $strFindMe);
// 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";
}
?>
Check with strpos() function, it is case sensitive!
if( strpos($strPar, $strFindMe) ) { //it return a boolean value
echo "String Found";
}
$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "THAT";//Find the position of the first occurrence of a case-insensitive substring in a string
$exists = strpos($strPar, $strFindMe);
if ($exists !== false) {
// substring is in the main string
}
Related
PHP code:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
if (in_array($search, $array)) {
echo "success";
}
else
echo "fail";
I want the success output. How is it possible?
You can use array_reduce and stripos to check all the values in $array to see if they are present in $search in a case-insensitive manner:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
if (array_reduce($array,
function ($c, $i) use ($search) {
return $c || (stripos($search, $i) !== false);
},
false))
echo "success";
else
echo "fail";
Output:
success
Edit
Since this is probably more useful wrapped in a function, here's how to do that:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
function search($array, $search) {
return array_reduce($array,
function ($c, $i) use ($search) {
return $c || (stripos($search, $i) !== false);
},
false);
}
if (search($array, $search))
echo "success";
else
echo "fail";
$search2 = "michael";
if (search($array, $search2))
echo "success";
else
echo "fail";
Output
success
success
Here's an in_array-esque function that will ignore case and bail early on a match:
function search_array($search, $arr) {
foreach ($arr as $item) {
if (stripos($search, $item) !== false) {
return 1;
}
}
return 0;
}
$search = "Who is KMichaele test";
$array = ["john", "michael", "adam"];
if (search_array($search, $array)) {
echo "success\n";
}
else {
echo "fail\n";
}
Output
success
You can do this with a simple regx
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
$regex = '/\b('.implode('|', $array).')\b/i';
///\b(john|michael|adam)\b/i
$success = preg_match($regex, $search);
The Regex is simple
\b - matches word boundary
| or
the flag \i, case insensitive
Essential match any of the words in the list.
By using the boundary the word michael will not match kmichael for example. If you want partial word matches, just remove those.
Sandbox without the word boundry
If you include the 3rd argument
$success = preg_match($regex, $search,$match);
You can tell what the matches were. And last but not lest you can reduce it down to one line
$success = preg_match('/\b('.implode('|', $array).')\b/i', $search);
$string = "/*123123123*/";
$string = "123/*123123*/";
$string = "/*123123*/123";
$string = "123/*123123*/123";
for all these variants, I need to return true, so /* and */ are present in string.
Tried
if(preg_match("/(/*&*/)/i", $string)){
$flag=true;
}
else{
$flag=false;
}
but it didn't work out :c
Use substr_count(): http://php.net/manual/en/function.substr-count.php
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
You can use:
if (preg_match('%/\*.+\*/%', $string)) {
$flag = true;
} else {
$flag = false;
}
Regex Demo and Explanation
I used
if((strpos($string,"/*")!== FALSE) && (strpos($string,"*/")!== FALSE)){
$flag=true;
}
else{
$flag=false;
}
Don't actually know what is better to use, code above, or code with regexp by Pedro Lobito:
if (preg_match('%/\*.+\*/%', $string)) {
$flag = true;
} else {
$flag = false;
}
Say I have an integer 88123401, and I want to determine whether it includes a sequence of numbers like 1234, 23456, 456789, or the like of any length and from any beginning of numbers.. Is this possible at all in PHP, and if so, how would one go about finding out?
Some function with a for so you go through all the string comparing each character with its predecessor.
function doesStringContainChain($str, $n_chained_expected)
{
$chained = 1;
for($i=1; $i<strlen($str); $i++)
{
if($str[$i] == ($str[$i-1] + 1))
{
$chained++;
if($chained >= $n_chained_expected)
return true;
}else{
$chained = 1;
}
}
return false;
}
doesStringContainChain("6245679",4); //true
doesStringContainChain("6245679",5); //false
use a loop and use the answer of #jtheman
$mystring = '88123401';
$findme = array(123,2345,34567);
foreach ( $findme as $findspecificnum ) {
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
}
keeping it easy and straight forward.
Treat the number as a string and search with strpos().
Example:
$mystring = '88123401';
$findme = '1234';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
Source: http://php.net/manual/en/function.strpos.php
This might help you:
$number = "88123401";
$splittedNumbers = str_split($number);
$continuous = false;
$matches[0] = '';
$i = 0;
do {
if ((int)(current($splittedNumbers) + 1) === (int)next($splittedNumbers)) {
if($continuous) {
$matches[$i] .= current($splittedNumbers);
}
else {
$matches[$i] .= prev($splittedNumbers) . next($splittedNumbers);
$continuous = true;
}
} else {
$continuous = false;
$matches[++$i] = '';
}
prev($splittedNumbers);
} while (!(next($splittedNumbers) === false));
print_r(array_values(array_filter($matches)));
This lists all the matches that are sequential in an array. We can process further based on the results.
Result:
Array
(
[0] => 1234
[1] => 01
)
How can I check if a sentence contains a word. I used names sentence and word instead of string and substring expressly. For example:
for sentence
$s = "Ala makota, a kot ma przesrane";
calling function
checkIfContains("kota",$s)
returns false.
But for
checkIfContains("makota",$s)
returns true.
If you're looking to match only full words, you'll need a regular expression to accomplish this. Try the following:
<?php
function checkIfContains( $needle, $haystack ) {
return preg_match( '#\b' . preg_quote( $needle, '#' ) . '\b#i', $haystack ) !== 0;
}
You need strpos.
if (strpos($s, 'kota') !== false) {
}
Or if you insist..
function checkIfContains($needle, $haystack) {
return (strpos($haystack, $needle) !== false);
}
For full words you could consider regex:
if (preg_match('/\bkota\b/i', $s)) { }
I'd use explode to separate the string into an array based on a character (" " in this case).
function checkIfContains($toTest, $toCheck)
{
// Check if length of either string is zero for validation purposes
if(strlen($toTest) == 0 || strlen($toCheck) == 0)
{
return false;
}
$exploded = explode(" ", $toCheck);
foreach($exploded as $word)
{
if($word == $toTest)
{
// Found a match, return true!
return true;
}
}
// None matched, return false
return false;
}
You can try :
function checkIfContains($needle, $haystack) {
// Remove punctuation marks
$haystack = preg_replace('/[^a-zA-Z 0-9]+/', '', $haystack);
// Explode sentence with space
$haystack = explode(' ', $haystack);
// Check if $needle exist
return in_array($needle, $haystack);
}
$string = "Ala makota, a kot ma przesrane";
checkIfInString("makota", $string);
function checkIfInString($needle, $haystack) {
$delimiters = ' ,.';
return in_array($needle, explode($haystack, $delimiters);
}
you can try like :
if(strpos($s,"kota") !== false){
echo true;
}
or :
function checkIfContains($string, $letter){
return strpos($string, $letter) !== false;
}
How do you use the strpos for an array of needles when searching a string? For example:
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpos($string, $find_letters) !== false)
{
echo 'All the letters are found in the string!';
}
Because when using this, it wouldn't work, it would be good if there was something like this
#Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
How to use:
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
if (strposa($string, $array, 1)) {
echo 'true';
} else {
echo 'false';
}
will return true, because of array "cheese".
Update: Improved code with stop when the first of the needles is found:
function strposa(string $haystack, array $needles, int $offset = 0): bool
{
foreach($needles as $needle) {
if(strpos($haystack, $needle, $offset) !== false) {
return true; // stop on first true result
}
}
return false;
}
$string = 'This string contains word "cheese" and "tea".';
$array = ['burger', 'melon', 'cheese', 'milk'];
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
str_replace is considerably faster.
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);
The below code not only shows how to do it, but also puts it in an easy to use function moving forward. It was written by "jesda". (I found it online)
PHP Code:
<?php
/* strpos that takes an array of values to match against a string
* note the stupid argument order (to match strpos)
*/
function strpos_arr($haystack, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($haystack, $what))!==false) return $pos;
}
return false;
}
?>
Usage:
$needle = array('something','nothing');
$haystack = "This is something";
echo strpos_arr($haystack, $needle); // Will echo True
$haystack = "This isn't anything";
echo strpos_arr($haystack, $needle); // Will echo False
The question, is the provided example just an "example" or exact what you looking for? There are many mixed answers here, and I dont understand the complexibility of the accepted one.
To find out if ANY content of the array of needles exists in the string, and quickly return true or false:
$string = 'abcdefg';
if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
echo 'at least one of the needles where found';
};
If, so, please give #Leon credit for that.
To find out if ALL values of the array of needles exists in the string, as in this case, all three 'a', 'b' and 'c' MUST be present, like you mention as your "for example"
echo 'All the letters are found in the string!';
Many answers here is out of that context, but I doubt that the intension of the question as you marked as resolved. E.g. The accepted answer is a needle of
$array = array('burger', 'melon', 'cheese', 'milk');
What if all those words MUST be found in the string?
Then you try out some "not accepted answers" on this page.
You can iterate through the array and set a "flag" value if strpos returns false.
$flag = false;
foreach ($find_letters as $letter)
{
if (strpos($string, $letter) !== false)
{
$flag = true;
}
}
Then check the value of $flag.
If you just want to check if certain characters are actually in the string or not, use strtok:
$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
// not found
} else {
// found
}
This expression searches for all letters:
count(array_filter(
array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)
You can try this:
function in_array_strpos($word, $array){
foreach($array as $a){
if (strpos($word,$a) !== false) {
return true;
}
}
return false;
}
You can also try using strpbrk() for the negation (none of the letters have been found):
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpbrk($string, implode($find_letters)) === false)
{
echo 'None of these letters are found in the string!';
}
This is my approach. Iterate over characters in the string until a match is found. On a larger array of needles this will outperform the accepted answer because it doesn't need to check every needle to determine that a match has been found.
function strpos_array($haystack, $needles = [], $offset = 0) {
for ($i = $offset, $len = strlen($haystack); $i < $len; $i++){
if (in_array($haystack[$i],$needles)) {
return $i;
}
}
return false;
}
I benchmarked this against the accepted answer and with an array of more than 7 $needles this was dramatically faster.
If i just want to find out if any of the needles exist in the haystack, i use
reusable function
function strposar($arrayOfNeedles, $haystack){
if (count(array_filter($arrayOfNeedles, function($needle) use($haystack){
return strpos($haystack, $needle) !== false;
})) > 0){
return true;
} else {
return false;
}
}
strposar($arrayOfNeedles, $haystack); //returns true/false
or lambda function
if (count(array_filter($arrayOfNeedles, function($needle) use($haystack){
return strpos($haystack, $needle) !== false;
})) > 0){
//found so do this
} else {
//not found do this instead
}
With the following code:
$flag = true;
foreach($find_letters as $letter)
if(false===strpos($string, $letter)) {
$flag = false;
break;
}
Then check the value of $flag. If it is true, all letters have been found. If not, it's false.
I'm writing a new answer which hopefully helps anyone looking for similar to what I am.
This works in the case of "I have multiple needles and I'm trying to use them to find a singled-out string". and this is the question I came across to find that.
$i = 0;
$found = array();
while ($i < count($needle)) {
$x = 0;
while ($x < count($haystack)) {
if (strpos($haystack[$x], $needle[$i]) !== false) {
array_push($found, $haystack[$x]);
}
$x++;
}
$i++;
}
$found = array_count_values($found);
The array $found will contain a list of all the matching needles, the item of the array with the highest count value will be the string(s) you're looking for, you can get this with:
print_r(array_search(max($found), $found));
Reply to #binyamin and #Timo.. (not enough points to add a comment..) but the result doesn't contain the position..
The code below will return the actual position of the first element which is what strpos is intended to do. This is useful if you're expecting to find exactly 1 match.. If you're expecting to find multiple matches, then position of first found may be meaningless.
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
$res=strpos($haystack, $query, $offset);
if($res !== false) return $res; // stop on first true result
}
return false;
}
Just an upgrade from above answers
function strsearch($findme, $source){
if(is_array($findme)){
if(str_replace($findme, '', $source) != $source){
return true;
}
}else{
if(strpos($source,$findme)){
return true;
}
}
return false;
}
<?php
$Words = array("hello","there","world");
$c = 0;
$message = 'Hi hello';
foreach ($Words as $word):
$trial = stripos($message,$word);
if($trial != true){
$c++;
echo 'Word '.$c.' didnt match <br> <br>';
}else{
$c++;
echo 'Word '.$c.' matched <br> <br>';
}
endforeach;
?>
I used this kind of code to check for hello, It also Has a numbering feature.
You can use this if you want to do content moderation practices in websites that need the user to type