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).
Related
I'm trying to see whether or not 2 strings match.
example: 1234.5678.9012.3456 => 5678.1234.3456 = match
This matches because the second string of number are also in the first one. I did this with the following code:
<?php
$haystack = '1234.5678.9012.3456';
$needle = '5678.1234.3456';
$regex = '/(?=.*'. str_replace(".",")(?=.*",$needle) .').*$/';
// regex looks like this /(?=.*5678)(?=.*1234)(?=.*3456).*$/
if(preg_match($regex, $haystack)){
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
Here is my problem, when there are duplicate numbers.
example: 1234.5678.9012.3456 => 5678.5678.3456 = dont match
1234.5678.5678.3456 => 5678.5678.3456 = match
The first example doesnt match because 5678 occurs twice but the first string only has 5678 once. In the second example 5678 occurs twice as well and therefor matches the second string.
My question: How could I change my regex,
You choose a very complicated way to do that. You can check what you want in a more simple way using array_diff:
var_dump(array_diff(explode('.', $needle), explode('.', $haystack)));
when the resulting array is empty the condition is true.
Try this:
<?php
$haystack = '1234.5678.9012.3456';
$needle = '5678.5678.3456';
$needle_array = explode(".", $needle);
//print_r($needle_array);
$haystack_array = explode(".", $haystack);
//print_r($haystack_array);
$intersect = array_intersect($needle_array, $haystack_array);
//print_r($intersect);
if(count($intersect) > 0){
echo "Match";
} else {
echo "Doesn't match";
}
?>
Sorry, a bit new to php. Have tried all I know, but failed and seeking expert help.
I have a string similar to this..
/%mydocs%/%myfolder%/%date%/%filename%.html
Basically the %vars% represents different strings and seperated by /, like a URL.
I need to find %date% (or any given variable) if it's present and it's position in the string, like it's at position 3 in the example above.
I tried this,
$date = preg_match( '%date%', '/%mydocs%/%myfolder%/%date%/%filename%.html');
But it's neither returning anything nor the position.
Any help, even some heads up to play with, will be appriciated.
strpos
<?php
$mystring = '/%mydocs%/%myfolder%/%date%/%filename%.html';
$findme = '%date%';
$pos = strpos($mystring, $findme);
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";
}
?>
Result:
The string '%date%' was found in the string '/%mydocs%/%myfolder%/%date%/%filename%.html' and exists at position 21
How about using preg_split:
$var = '%date%';
$str = '/%mydocs%/%myfolder%/%date%/%filename%.html';
$list = preg_split('#/#', $str, -1, PREG_SPLIT_NO_EMPTY);
for($i=0; $i<count($list); $i++) {
if ($list[$i] == $var) {
echo "Found $var at position ",$i+1,"\n";
}
}
output:
Found %date% at position 3
preg_match returns a boolean for whether there was a match or not, but you can pass a third parameter - $matches, which will contain the matches according to the regular expression provided.
You don't look to be using a regular expressions - for what you are doing you probably want to look at strpos instead. http://uk3.php.net/strpos
I want to check the first word of some sentences. If the first word are For, And, Nor, But, Or, etc, I want to skip the sentence.
Here's the code :
<?php
$sentence = 'For me more';
$arr = explode(' ',trim($sentence));
if(stripos($arr[0],'for') or stripos($arr[0],'but') or stripos($arr[0],'it')){
//doing something
}
?>
Blank result, Whats wrong ? thank you :)
Here, stripos will return 0 if the word is found (found at position 0).
It returns false if the word is not found.
You should write :
if(stripos($arr[0],'for') !== false or stripos($arr[0],'but') !== false or stripos($arr[0],'it') !== false){
//skip
}
Stripos returns the position on the first occurrence of the needle in the haystack
The first occurrence is at position 0, which evaluates to false.
Try this as an alternative
$sentence = 'For me more';
// make all words lowercase
$arr = explode(' ', strtolower(trim($sentence)));
if(in_array($arr[0], array('for', 'but', 'it'))) {
//doing something
echo "found: $sentence";
} else {
echo 'failed';
}
Perhaps use preg_filter if you are going to know what the string to be evaluated is (i.e. you don't need to parse out sentences).
$filter_array = array(
'/^for\s/i',
'/^and\s/i',
'/^nor\s/i',
// etc.
}
$sentence = 'For me more';
$result = preg_filter(trim($sentence), '', $filter_array);
if ($result === null) {
// this sentence did not match the filters
}
This allows you to determine a set of filter regex patterns to see if you have a match. Note that in this case I just used '' as "replacement" value, as you don't really care about actually making a replacement, this function just gives you a nice way to pas in an array of regular expressions.
I'm trying to find out if a string matches any of my bad words in my array IE:
$badWords = Array('bad', 'words', 'go', 'here');
$strToCheck = "checking this string if any of the bad words appear";
if (strpos($strToCheck, $badWords)) {
// bad word found
}
the issue is strpos can only check for a string and not an array, is there a method of doing this without looping through the array of badwords?
Not exactly, since all solutions inevitably must loop over your array, even if it's "behind the scenes". You can make a regular expression out of $badWords, but the runtime complexity will probably not be affected. Anyway, here's my regex suggestion:
$badWordsEscaped = array_map('preg_quote', $badWords);
$regex = '/'.implode('|', $badWordsEscaped).'/';
if(preg_match($regex, $strToCheck)) {
//bad word found
}
Note that I've escaped the words to protect against regex-injections, if they contain any special regex characters such as / or .
array_intersect() gives you the list of matching words:
if (count(array_intersect(preg_split('/\s+/', $strToCheck), $badWords))) {
// ...
}
in_array.
Read question wrong.
Simplest implementation is to call strpos() for each of the badwords:
<?php
$ok = TRUE;
foreach($badwords AS $word)
{
if( strpos($strToCheck, $word) )
{
$ok = FALSE;
break;
}
}
?>
Try This..
$badWords = array('hello','bad', 'words', 'go', 'here');
$strToCheck = 'i am string to check and see if i can find any bad words here';
//Convert String to an array
$strToCheck = explode(' ',$strToCheck);
foreach($badWords as $bad) {
if(in_array($bad, $strToCheck)) {
echo $bad.'<br/>';
}
}
the above code will return all matched bad words, you can further extend it to implement your own logic like replacing the bad words etc.
I have a string
8,7,13,14,16
Whats the easiest way to determine if a given number is present in that string?
$numberA = "13";
$string = "8,7,13,14,16";
if($string magic $numberA){
$result = "Yeah, that number is in there";
} else {
$result = "Sorry.";
}
Looking for magic.
<?php
in_array('13', explode(',', '8,7,13,14,16'));
?>
…will return whether '13' is in the string.
Just to elaborate: explode turns the string into an array, splitting it at each ',' in this case. Then, in_array checks if the string '13' is in the resulting array somewhere.
Another way, that might be more efficient for laaaaaaaarge strings, is using a regexp:
$numberA = "13";
$string = "8,7,13,14,16";
if(preg_match('/(^|,)'.$numberA.'($|,)/', $string)){
$result = "Yeah, that number is in there";
} else {
$result = "Sorry.";
}
if (strpos(','.$string.',' , ','.$numberA.',') !== FALSE) {
//found
}
Notice guard ',' chars, they will help to deal with '13' magic '1, 2, 133' case.
Make sure you match the full number in the string, not just part of it.
function numberInList($num, $list) {
return preg_match("/\b$num\b/", $list);
}
$string = "8,7,13,14,16";
numberInList(13, $string); # returns 1
numberInList(8, $string); # returns 1
numberInList(1, $string); # returns 0
numberInList(3, $string); # returns 0
A simple string search should do if you are just checking to find existence of the string. I dont speak php but i think this is how it could be done.
$mystring = '8,7,13,14,16';
$findme = '13';
if (preg_match('/(?>(^|[^0-9])'.$findme.'([^0-9]|$))/', $mystring)) {
$result = "Yeah, that number is in there";
} else {
$result = "Sorry.";
}