PHP: How to check if ANY are located in string? [duplicate] - php

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) {
}
}

Related

PHP: stripos doesn't find a value [duplicate]

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.

How to find the most used word in a string PHP [duplicate]

This question already has answers here:
Most used words in text with php
(4 answers)
Closed 5 years ago.
I'm trying to find the most used word in a string in PHP. The lyrics file is a string of lyrics.
//display the most used word in the lyrics file
$wordCount = str_word_count($lyrics);
$wordCountArray = array();
foreach($wordCount as $word){
if(!array_key_exists($word, $wordCountArray)){
$wordCountArray[$word] = 1;
}else{
$wordCountArray[$word] += 1;
}
}
arsort($wordCountArray);
print_r($wordCountArray[0]);
I'm getting errors with this code and I'm wondering what isn't working. I need the actual word and not the number.
I think you meant:
$words = str_word_count($lyrics, 1)
foreach($words as $word) {
Simple example
<?php
$string = 'Hello hi hello abcd abc hoi bye hello';
$string = strtolower($string);
$words = explode(' ',$string);
var_dump(array_count_values($words));

Search a letter in a list of words?

I have an array called 'words' storing many words.
For example:
I have 'systematic', 'سلام','gear','synthesis','mysterious', etc.
NB: we have utf8 words too.
How to query efficiently to see which words include letters 's','m','e' (all of them) ?
The output would be:
systematic,mysterious
I have no idea how to do such a thing in PHP. It should be efficient because our server would suffer otherwise.e.
Use a regular expression to split each string into an array of characters, and use array_intersect() to find out if all the characters in your search array is present in the split array:
header('Content-Type: text/plain; charset=utf8');
$words = array('systematic', 'سلام','gear','synthesis','mysterious');
$search = array('s','m','e');
foreach ($words as $word) {
$char_array = utf8_str_split($word);
$contains = array_intersect($search, $char_array) == $search;
echo sprintf('%s : %s', $word, (($contains) ? 'True' : 'False'). PHP_EOL);
}
function utf8_str_split($str) {
return preg_split('/(?!^)(?=.)/u', $str);
}
Output:
systematic : True
سلام : False
gear : False
synthesis : False
mysterious : True
Demo.
UPDATE: Or, alternatively, you could use array_filter() with preg_match():
$array = array_filter($words, function($item) {
return preg_match('~(?=[^s]*s)(?=[^m]*m)(?=[^e]*e)~u', $item);
});
Output:
Array
(
[0] => systematic
[4] => mysterious
)
Demo.
This worked to me:
$words = array('systematic', 'سلام','gear','synthesis','mysterious');
$letters=array('s','m', 'e');
foreach ($words as $w) {
//print "lets check word $w<br>";
$n=0;
foreach ($letters as $l) {
if (strpos($w, $l)!==false) $n++;
}
if ($n>=3) print "$w<br>";
}
It returns
systematic
mysterious
Explanation
It uses nested foreach: one for the words and the other one for the letters to be matched.
In case any letter is matched, the counter is incremented.
Once the letters loop is over, it checks how many matches were there and prints the word in case it is 3.
Something like this:
$words = array('systematic', 'سلام','gear','synthesis','mysterious');
$result=array();
foreach($words as $word){
if(strpos($word, 's') !== false &&
strpos($word, 'm') !== false &&
strpos($word, 'e') !== false){
$result[] = $word;
}
}
echo implode(',',$result); // will output 'systematic,mysterious'
Your question is wide a little bit.
What I understand from your question that's those words are saved in a database table, so you may filter the words before getting them into the array, using SQL like function.
in case you want to search for a letters in an array of words, you could loop over the array using foreach and each array value should be passed to strpos function.
http://www.php.net/function.strpos
why not use PREG_GREP
$your_array = preg_grep("/[sme]/", $array);
print_r($your_array);
WORKING DEMO

One regex, multiple replacements [duplicate]

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;

Find exact string in string - PHP

How do I find exact 2, in a string using strpos? Is it possible using strpos? The example below returns "Found" even though the match is NOT exact to what I need. I understand 2, is matching with 22,. It should return "Not Found". I am matching ID's in this example.
$string = "21,22,23,26,";
$find = "2,";
$pos = strpos($string, $find);
if ($pos !== false) {
echo "Found";
} else {
echo "Not Found";
}
Unless the string is enormous, make an array and search it:
$string = "21,22,23,26,";
$arr = explode(",", $string);
// array_search() returns its position in the array
echo array_search("2", $arr);
// null output, 2 wasn't found
Actually, in_array() is probably faster:
// in_array() returns a boolean indicating whether it is found or not
var_dump(in_array("2", $arr));
// bool(false), 2 wasn't found
var_dump(in_array("22", $arr));
// bool(true), 22 was found
This will work as long as your string is a comma-delimited list of values. If the string is really long, making an array may be wasteful of memory. Use a string manipulation solution instead.
Addendum
You didn't specify, but if by some chance these strings came from a database table, I would just add that the appropriate course of action would be to properly normalize it into another table with one row per id rather than store them as a delimited string.
Try with explode and in_array
Example:
$string = "21,22,23,26,";
$string_numbers = explode(",", $string);
$find = 2;
if (in_array($find, $string_numbers)) {
echo "Found";
} else {
echo "Not Found";
}
You can use preg_match if you want to avoid arrays.
$string = "21,22,23,26,";
$find = '2';
$pattern = "/(^$find,|,$find,|,$find$)/";
if (0 === preg_match($pattern, $string)) {
echo "Not Found";
} else {
echo "Found";
}
This will find your id at beginning, middle or at the end of the string. Of course, I am assuming $string does not contain characters other than numbers and commas (like spaces).

Categories