I would like to know what is the best way to know if my substring is in the string.
So, I can has these kind of value :
"abcd.tif"
"abcd_A.tif"
"abcd_B.tif"
"abcd_VP.tif"
I would detect if "_A" or "_B" or "_VP" is present in the string.
What's the best way ? Using a combination of substr and strlen ?
or use regex ?
Use strpos, which will give you the 0-indexed position of the needle in the string. If it's not in the string, strpos returns false. (There is also case-insensitive stripos).
However, you can only check one needle at a time. If you'd like to check for any of the three simultaneously you can either use a loop or write the terser but less efficient way:
preg_match('/_A|_B|_VP/', $str)
...which will return true if any of those three strings matches.
The most efficient way (I know of :P) is strpos.
$s = 'abcd_VP.tif';
if (strpos('_A', $s) !== false) {
// do your thing
}
You can do a simple || after this, it won't be as short, but it will be much quicker than regex:
$s = 'abcd_VP.tif';
if ((strpos('_A', $s) !== false) || (strpos('_B', $s) !== false) || (strpos('_VP') !== false)) {
// do your thing
}
Use OR operation like (_A)|(_VP) etc. check this question as a hint: Regular Expressions: Is there an AND operator? , to use 'OR' in regular expression.
Related
Can't find a solution to this which seems simple enough. I have user input field and want to check the user has prefixed the code asked for with an S (example code S123456 so I want to check to make sure they didn't just put 123456).
// Function to check string starting with s
if (isset($_REQUEST['submitted'])) { $string=$_POST['required_code'];function startsWith ($string, $startString){$len = strlen($startString);return (substr($string, 0, $len) === $startString);
}
// Do the check
if(startsWith($string, "s"))echo "Code starts with a s";else echo "Code does not start with a s";}
The problem is if the user inputs an upper case S this is seen as not being a lower case s.
So I can get round this using
$string = strtolower($string);
So if the user inputs an uppercase S it gets converted to lower case before the check. But is this the best way? Is there not someway to say S OR s?
Any suggestions?
What you could do instead of creating your own function, is using stripos. Stripos tries to find the first occurrence of a case-insensitive substring.
So as check you could have:
if(stripos($string, "s") === 0)
You need 3 equal signs, since stripos will return false (0) if it can't find the substring.
Take your pick; there are many ways to see if a string starts with 'S'. Some of them case-sensitive, some not. The options below should all work, although I wouldn't consider any of them better than your current solution. stripos() is probably the 'cleanest' check though. If you need multibyte support, there's also the mb_stripos() variant.
(Although; keep in mind that stripos() can also return false. If you're going with that option, always use the stricter "identical" operator ===, instead of == to prevent type juggling.)
if (stripos($string, 's') === 0) {
// String starts with S or s
} else {
// It does not
}
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
if (in_array(substr($string, 0, 1), ['S', 's'], true)) // ...
if (preg_match('/^s/i', $string)) // ...
// Many other regexp patterns also work
Thanks all, it was
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
I was looking for I had tried
if (str_starts_with($string, 's' || 'S')) // ...
I was asked on an interview what would be the fastest way to extract the comparison operator between two statements.
For example rate>=4 the comparison operator is '>=' it should be able to extract '>','<','!=','=','<=','>=','='
The function must return the comparison operator.
This is what I wrote, and they marked it as wrong.
function extractcomp($str)
{
$temp = [];
$matches = array('>','<','!','=');
foreach($matches as $match)
{
if(strpos($str,$match)!== false)
{
$temp[] = $match;
}
}
return implode('',$temp);
}
Does anyone have a better way?
you can read character by character once you hit the first occurrence you can determine what's gonna be the next character i.e.:
$ops = ['>','<','!','='];
$str = "rate!=4";
foreach($ops as $op)
{
if(($c1 = strpos($str, $op)) !== false)
{
$c2 = $str[$c1++] . (($str[$c1] == $ops[3]) ? $str[$c1] : "");
break;
}
}
echo $c2;
So if the first search character is ">" you can only assume the 2nd one is gonna be "=" or it doesn't exist. So you get the index of 1st character and increment it and check if the 2nd character exists in our search array or not. Then return the value. this will loop until it finds the 1st occurrence then breaks.
EDIT:
here's another solution:
$str = "rate!=4";
$arr = array_intersect(str_split($str), ['>','<','=','!']);
echo current($arr).(end($arr) ? end($arr) : '');
not as fast as the loop but definitely decreases the bloat code.
There's always a better way to optimize the code.
Unless they have some monkeywrenching strings to throw at this custom function, I recommend trim() with a ranged character mask. Something like echo trim('rate>=4',"A..Za..z0..9"); would work for your sample input in roughly half the time.
Code: (Demo)
function extractcomp($str){
return trim($str,"A..Za..z0..9");
}
echo extractcomp("rate>=4");
Regarding regex, better efficiency in terms of step count with preg_match() would be to use a character class to match the operators.
Assuming only valid operators will be used, you can use /[><!=]+/ or if you want to tighen up length /[><!=]{1,3}/
Just 8 steps on your sample input string. Demo
This is less strict than Andreas' | based pattern, but takes fewer steps.
It depends on how strict the pattern must be. My pattern will match !==.
If you want to improve your loop method, write a break after you have matched the entire comparison operator.
Actually, you are looping the operators. That would have been their issue (or one of them). Your method will not match ==. I'm not sure if that is a possible comparison (it is not in your list).
How do i make a if statement which checks if the string contains a forward slash?
$string = "Test/Test";
if($string .......)
{
mysql_query("");
}
else
{
echo "the value contains a invalid character";
}
You can use strpos, which will make sure there is a forward slash in the string but you need to run it through an equation to make sure it's not false. Here you can use strstr(). Its short and simple code, and gets the job done!
if(strstr($string, '/')){
//....
}
For those who live and die by the manual, when the haystack is very large, or the needle is very small, it is quicker to use strstr(), despite what the manual says.
Example:
Using strpos(): 0.00043487548828125
Using strstr(): 0.00023317337036133
if(strpos($string, '/') !== false) {
// string contains /
}
From the PHP manual of strstr:
Note:
If you only want to determine if a particular needle occurs within
haystack, use the faster and less memory intensive function strpos()
instead.
Use strpos()
If it doesn't return false, the character was matched.
I compared strpos() results with 0. Somehow comparison with false did not work for me.
if (strpos($t, '/') !== 0) {
echo "No forward slash!";
}
This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 26 days ago.
In SQL we have NOT LIKE %string%
I need to do this in PHP.
if ($string NOT LIKE %word%) { do something }
I think that can be done with strpos()
But can’t figure out how…
I need exactly that comparission sentence in valid PHP.
if ($string NOT LIKE %word%) { do something }
if (strpos($string, $word) === FALSE) {
... not found ...
}
Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.
Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.
Use strpos. If the string is not found it returns false, otherwise something that is not false. Be sure to use a type-safe comparison (===) as 0 may be returned and it is a falsy value:
if (strpos($string, $substring) === false) {
// substring is not found in string
}
if (strpos($string, $substring2) !== false) {
// substring2 is found in string
}
use
if(stripos($str,'job')){
// do your work
}
<?php
// Use this function and Pass Mixed string and what you want to search in mixed string.
// For Example :
$mixedStr = "hello world. This is john duvey";
$searchStr= "john";
if(strpos($mixedStr,$searchStr)) {
echo "Your string here";
}else {
echo "String not here";
}
Kind of depends on your data, doesn't it? strpos('a foolish idea','fool') will show a match, but may not be what you want. If dealing with words, perhaps
preg_match("!\b$word\b!i",$sentence)
is wiser. Just a thought.
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