I'm trying to figure out how I can compare values from an array against a particular string.
Basically my values look like chrisx001, chrisx002, chrisx003, chrisx004, bob001
I was looking at fnmatch() but I'm not sure this is the right choice, as what I want to do is keep chrisx--- but ignore bob--- so I need to wildcard the last bit, is there a means of doing this where I can be like
if($value == "chrisx%"){/*do something*/}
and if thats possible is it possible to double check the % value as int or similar in other cases?
Regex can tell you if a string starts with chrisx:
if (preg_match('/^chrisx/', $subject)) {
// Starts with chrisx
}
You can also capture the bit after chrisx:
preg_match('/^chrisx(.*)/', $subject, $matches);
echo $matches[1];
You could filter your array to return a second array of only those entries beginning whith 'chris' and then process that filtered array:
$testData = array ( 'chrisx001', 'chrisx002', 'chrisx003', 'chrisx004', 'bob001');
$testNeedle = 'chris';
$filtered = array_filter( $testData,
function($arrayEntry) use ($testNeedle) {
return (strpos($arrayEntry,$testNeedle) === 0);
}
);
var_dump($filtered);
Related
I have a string like abcdefg123hijklm. I also have an array which contains several strings like [456, 123, 789].
I want to check if the number in the middle of abcdefg123hijklm exists in the array.
How can I do that? I guess in_array() won't work.
So you want to check if any substring of that particular string (lets call it $searchstring) is in the array?
If so you will need to iterate over the array and check for the substring:
foreach($array as $string)
{
if(strpos($searchstring, $string) !== false)
{
echo 'yes its in here';
break;
}
}
See: http://php.net/manual/en/function.strpos.php
If you want to check if a particular part of the String is in the array you will need to use substr() to separate that part of the string and then use in_array() to find it.
http://php.net/manual/en/function.substr.php
Another option would be to use regular expressions and implode, like so:
if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
echo("Yes, the string '{$matches[0]}' was found in the search string.");
else
echo("None of the strings in the array were found in the search string.");
It's a bit less code, and I would expect it to be more efficient for large search strings or arrays, since the search string will only have to be parsed once, rather than once for every element of the array. (Although you do add the overhead of the implode.)
The one downside is that it doesn't return the array index of the matching string, so the loop might be a better option if you need that. However, you could also find it with the code above followed by
$match_index = array_search($matches[0], $array);
Edit: Note that this assumes you know your strings aren't going to contain regular expression special characters. For purely alphanumeric strings like your examples that will be true, but if you're going to have more complex strings you would have to escape them first. In that case the other solution using a loop would probably be simpler.
You can do it reversely. Assume your string is $string and array is $array.
foreach ($array as $value)
{
// strpos can return 0 as a first matched position, 0 == false but !== false
if (strpos($string, $value) !== false)
{
echo 'Matched value is ' . $value;
}
}
Use this to get your numbers
$re = "/(\d+)/";
$str = "abcdefg123hijklm";
preg_match($re, $str, $matches);
and ( 123 can be $matches[1] from above ):
preg_grep('/123/', $array);
http://www.php.net/manual/en/function.preg-grep.php
I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.
I am trying to figure out how to match any words within an array. For example, the code bellow works for finding "Test Name" within an array but does not find "Another Test Name" (due to the word "Another") within the array. Any ideas?
if (in_array($html[$i], $eventsarray))
{
$topeventaa = "yes";
}
else
{
$topeventaa = "no";
}
Taken from http://php.net/manual/en/function.in-array.php
<?php
/**
* Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
*
* #param string $string Needle to find
* #param array $array Haystack to look through
* #result array Returns the elements that the $string was found in
*/
function find ($string, $array = array ())
{
foreach ($array as $key => $value) {
unset ($array[$key]);
if (strpos($value, $string) !== false) {
$array[$key] = $value;
}
}
return $array;
}
?>
If you want to match any of the words to those in your array, you may want to use explode on your string and then check each token as you do in your example.
We probably need more information, but you can create variable with the pattern matching you need with preg_match and pass it as the argument in your search.
preg_replace and str_replace may be helpful, depending on what exactly you're trying to accomplish.
You may want to look into recursive function calls, like when traversing through all the directories within a directory tree.
I'd splice the array up to the index where it was found, leaving the remainder to be passed back into the same function to search through again.
Depending on what results you want from knowing the number of occurrences of words within a string could we then start to break down the problem and write some code.
Justin, there's no direct way--no existing built-in function--to do what I believe you seek; you must iterate over the array yourself, along the lines of
$topeventaa = "no";
for ($eventsarray as $key=>$value){
if (0 <= strpos($html[$i], $eventsarray[$key])) {
$topeventaa = "yes";
break;
}
}
Use preg_grep instead of in_array to find all elements of an array matching a given pattern.
Please excuse my noob-iness!
I have a $string, and would like to see if it contains any one or more of a group of words, words link ct, fu, sl** ETC. So I was thinking I could do:
if(stristr("$input", "dirtyword1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
elseif(stristr("$input", "dirtyWord1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord2");
}
...ETC. BUT, I don't want to have to keep doing if/elseif/elseif/elseif/elseif...
Can't I just do a switch statement OR have an array, and then simply say something like?:
$dirtywords = { "f***", "c***", w****", "bit**" };
if(stristr("$input", "$dirtywords"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
I'd appreciate any help at all
Thank you
$dirty = array("fuc...", "pis..", "suc..");
$censored = array("f***", "p***", "s***");
$input= str_ireplace($dirty, $censored , $input);
Note, that you don't have to check stristr() to do a str_ireplace()
http://php.net/manual/en/function.str-ireplace.php
If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search.
Surely not the best solution since I don't know too much PHP, but what about a loop ?
foreach (array("word1", "word2") as $word)
{
if(stristr("$input", $word))
{
$input = str_ireplace("$input", $word" "thisWillReplaceDirtyWord");
}
}
When you have several objects to test, think "loop" ;-)
I am trying to create a script that checks if a certain value is in a comma delimited string, and if the value is present, it should return true else it should return false.
Basically, I am trying to check if a user has voted for a specific person before, and if so, they cannot vote again, if they have not, vote and then add their uid to the database.
I am using explode to get all the values into an array, but I am unsure about the checking function, I have a few ideas but this is quite an important script so I wanted to see if there is a better way of going about it.
$test = "john,jack,tom";
$exploded = explode(",",$test);
$hostID = "john";
foreach($exploded as $one){
if($one == $hostID){
$return = TRUE;
}else{
$return = FALSE;
};
};
Thanx in advance!
You could use in_array.
Some people prefer to use lowercase true and false.
The semicolon after } is not needed
$return = TRUE does not actually stop the function. Maybe you do return $return.
Some people like to put spaces after comma's and keywords (e.g. foreach, if, else)
Some people prefer single quotes over double quotes
Code:
function find_name($name, $list)
{
$exploded = explode(',', $list);
return in_array($name, $exploded);
}
var_dump(find_name('john', 'john,jack,tom'));
?>
As Sjoerd says, in his very good advice.
function find_name( $needle , $haystack ) {
if( strpos( $haystack , $needle )===false )
return false;
return in_array( $needle , explode( ',' , $haystack ) );
}
Test cases:
// find_name( 'john' , 'peter,mark,john' );
true
// find_name( 'peter' , 'mark,john' );
false
EDITED: As per advice from Gordon.
You could also use
strpos — Find position of first occurrence of a string
instead:
return strpos('john,jack,tom', 'barney'); // returns FALSE
Note that the function returns the position if the string was found, so searching for john will return zero, which would be FALSE if you compare it for equality (==). In other words use the identity comparator (===).
As Lucanos correctly points out, there is chance to get false positives when using strpos if the searched name is part of a longer name, e.g. searching for jean only would also find jean-luc. You could add a comma at the end of the haystack string and search for jean, though, but then again, it feels hackish. So it's likely better to use in_array.