This question already has answers here:
php 5 strpos() difference between returning 0 and false?
(5 answers)
Closed 4 years ago.
I need to find one of the three words even if written at the beginning of the string and not just in the middle or at the end.
This is my code:
<?php
$string = "one test";
$words = array( 'one', 'two', 'three' );
foreach ( $words as $word ) {
if ( stripos ( $string, $word) ) {
echo 'found<br>';
} else {
echo 'not found<br>';
}
}
?>
If $string is "one test" the search fails;
if $string is "test one" the search is good.
Thank you!
stripos can return a value which looks like false, but is not, i.e. 0. In your second case, the word "one" matches "one test" at position 0 so stripos returns 0, but in your if test that is treated as false. Change your if test to
if ( stripos ( $string, $word) !== false ) {
and your code should work fine.
Related
I have tried to filter the string from the array which consists of the word DEVICE.
I have used the following technique to check whether there is a word called having DEVICE in the array but it prints
Match Not found
even though there are strings having word DEVICE.
Here is the attempt that I have tried:
$output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
$string = 'DEVICE';
foreach ($output as $out) {
if (strpos($string, $out) !== FALSE) {
echo "Match found";
return true;
}
}
echo "Match Not found!";
return false;
Required Output:
The output should be:
Match Found.
And also I want to display the list of the items that consist of the word DEVICE like:
computer DEVICE
mobile DEVICE
What correction do I need here?
A non looping way to solve it is to use preg_grep which is regex on arrays.
The pattern searches for "device" in a case insensitive way and returns any strings that have device in it.
$output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
$string = 'DEVICE';
$devices = preg_grep("/" . $string . "/i", $output);
Var_dump($devices);
Output
array(2) {
[2]=>
string(15) "computer DEVICE"
[3]=>
string(13) "mobile DEVICE"
}
https://3v4l.org/HkQcu
You've interchanged the arguments in the strpos(). The word to be searched is second argument in the function and the string is first.
int strpos (string $haystack , mixed $needle [, int $offset = 0 ])
Use the code below to get required output:
$output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
$string = 'DEVICE';
foreach ($output as $out) {
if (strpos($out, $string) !== FALSE) {
// You can also print the matched word using the echo statement below.
echo "Match found in word: {$out} <br/>";
return true;
}
}
echo "Match Not found!";
return false;
You have the position of the strpos fuction's arguments reversed. From php.net:
int strpos (string $haystack , mixed $needle [, int $offset = 0 ])
Therefore you should replace LINE 5 with the following
if (strpos($out, $string) !== FALSE) {
[1] https://secure.php.net/manual/en/function.strpos.php
Your issue is that your strpos() arguments are backwards. The API is
int strpos( string $haystack, mixed $needle [, int $offset = 0 ] )
As to your other question...
...also I want to display the list of the items that I consists of the word DEVICE
you could create an array of the matching elements via array_filter()
$string = 'DEVICE';
$filtered = array_filter($output, function($out) use ($string) {
return strpos($out, $string) !== false;
});
echo implode(PHP_EOL, $filtered);
if (count($filtered) > 0) {
echo 'Match found';
return true;
}
echo 'Match Not found!';
return false;
If you want to access the filtered array (of strings containing DEVICE), then you can no longer enjoy the performance benefits of an early return. You must iterate the entire input array -- with a classic loop or an array iterating function. I must state that your requirements do not call for the might of a regular expression; making iterated regex evaluations should be reserved for cases where simpler, native string functions are less suitable.
Boiled down, you need to make iterated case-sensitive checks and include strings which contain your qualifying keyword.
From PHP7.4, arrow functions allow more concise anonymous functions syntax and allow the omission of a use() call.
From PHP8, str_contains() is available and is perfectly suited to your required matching.
To find out if any strings qualified, just check the boolean evaluation of your output array.
Code: (Demo)
$input= [
'football GAME',
'cricket GAME',
'computer DEVICE',
'mobile DEVICE'
];
$needle = 'DEVICE';
$output = array_filter($input, fn($haystack) => str_contains($haystack, $needle));
var_export(
[
'filtered' => $output,
'found' => $output ? 'yes' : 'no'
]
);
Output:
array (
'filtered' =>
array (
2 => 'computer DEVICE',
3 => 'mobile DEVICE',
),
'found' => 'yes',
)
I am doing text analysis. I have a table having positive words.The records are being fetched one by one and imploded in an array through mysqli_fetch_array.
while(($rowx = mysqli_fetch_array($resultx,MYSQLI_NUM)))
{
$wordx = implode("", $rowx);
if(strpos($text, $wordx) !== FALSE)
{
$count1 = substr_count($text, $wordx);
$pos_prob += .2 * $count1;
echo "pos prob is".$pos_prob;
}
}
But strpos is not able to match the string that is being fetched from the table.i.e. if text is "It's an excellent book" the if condition is never true. Even though the word excellent is present in the table. And if I hard code the value $wordx as
$wordx='excellent';
Only then it works. Does anyone has any idea why this is happening? :( Any help would be much appreciated :)
I don't understand the need to implode each row. My assumption is that each row has one word.
Simple strpos text matching example:
<?php
$words = array(
'big',
'fat',
'mamma'
);
$text = 'One day fat foo walked to the bar';
$matches = array();
foreach($words as $word) {
if(strpos($text, $word) !== false)
$matches[] = $word;
}
var_dump($matches);
Output:
array (size=1)
0 => string 'fat' (length=3)
Note that this would also match word parts and be case sensitive, so not ideal. For example: 'fat' is contained in the words: 'father', 'infatuated' and 'marrowfat'.
This question already has answers here:
PHP strpos check against many
(3 answers)
Closed 8 years ago.
I am trying to see if any of a list of items are located in a PHP string. I know how to use strpos to test against one item:
if (strpos($string, 'abc') !== FALSE) {
But, how would I test, for example, if either 'abc' or 'def' appear in the $string?
<?php
$string=" fish abc cat";
if (preg_match("/abc|def/", $string) === 1){
echo 'match';
}
will echo match if either abc or def is found in the string
Without using preg_match(), you can't really do that. If you have some sort of delimiter, you can turn it into an array:
$string = 'I have abc and jkl and xyz.';
$string_array = explode(' ', $string);
$needed_array = array('abc', 'jkl', 'xyz');
$found = false;
foreach($needed_array as $need){
if( in_array($need, $string_array) ){
$found = true;
break;
}
}
Try storing all of your search strings into an array and then loop thru the string that you want to be searched.
$items = array('abcs', 'def');
for($i=0;$i<count($items);$i++) {
if(strpos($string, $items[$i]) !== FALSE) {
}
}
This question already has answers here:
Parse through a string php and replace substrings
(2 answers)
Closed 9 years ago.
OK, that's what I need :
Get all entries formatted like %%something%%, as given by the regex /%%([A-Za-z0-9\-]+)%%/i
Replace all instances with values from a table, given the index something.
E.g.
Replace %%something%% with $mytable['something'], etc.
If it was a regular replacement, I would definitely go for preg_replace, or even create an array of possible replacements... But what if I want to make it a bit more flexible...
Ideally, I'd want something like preg_replace($regex, $mytable["$1"], $str);, but obviously it doesn't look ok...
How should I go about this?
Code:
<?php
$myTable = array(
'one' => '1!',
'two' => '2!',
);
$str = '%%one%% %%two%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
if (isset($myTable[$matches[1]]))
return $myTable[$matches[1]];
else
return $matches[0];
},
$str
);
echo $str;
Result:
1! 2! %%three%%
if you don't want to tell upper from lower,
<?php
$myTable = array(
'onE' => '1!',
'Two' => '2!',
);
$str = '%%oNe%% %%twO%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
$flipped = array_flip($myTable);
foreach ($flipped as $v => $k) {
if (!strcasecmp($k, $matches[1]))
return $v;
}
return $matches[1];
},
$str
);
echo $str;
Unfortunately, for some strange reason the regex method isn't working for me with UTF-8 (preg_replace + UTF-8 doesn't work on one server but works on another).
What would be the most efficient way to accomplish my goal without using regex?
Just to make it as clear as possible, for the following set of words:
cat, dog, sky
cats would return false
the sky is blue would return true
skyrim would return false
Super short example but it's the way I'd do it without Regex.
$haystack = "cats"; //"the sky is blue"; // "skyrim";
$needles = array("cat", "dog", "sky");
$found = false;
foreach($needles as $needle)
if(strpos(" $haystack ", " $needle ") !== false) {
$found = true;
break;
}
echo $found ? "A needle was found." : "A needle was not found.";
My initial thought is to explode the text on spaces, and then check to see if your words exist in the resulting array. Of course you may have some punctuation leaking into your array that you'll have to consider as well.
Another idea would be to check the strpos of the word. If it's found, test for the next character to see if it is a letter. If it is a letter, you know that you've found a subtext of a word, and to discard this finding.
// Test online at http://writecodeonline.com/php/
$aWords = array( "I", "cat", "sky", "dog" );
$aFound = array();
$sSentence = "I have a cat. I don't have cats. I like the sky, but not skyrim.";
foreach ( $aWords as $word ) {
$pos = strpos( $sSentence, $word );
// If found, the position will be greater than or equal to 0
if ( !($pos >= 0) ) continue;
$nextChar = substr( $sSentence , ( $pos + strlen( $word ) ), 1 );
// If found, ensure it is not a substring
if ( ctype_alpha( $nextChar ) ) continue;
$aFound[] = $word;
}
print_r( $aFound ); // Array ( [0] => I [1] => cat [2] => sky )
Of course the better solution is to determine why you cannot use regex, as these solutions will be nowhere near as efficient as pattern-seeking would be.
If you are simply trying to find if a word is in a string you could store the string in a variable (If printing the string print the variable with the string inside instead) and use "in". Example:
a = 'The sky is blue'
The in a
True