I am looking for function which does this option:
preg_match("/^{$STRING}/i", ...)
but, without regular expression, and there must be the ^ in the first, which means that this expression will be false:
$search = "hi", $search_in "ahi";
it must be at the start of the string.
Not sure I understood your request well... But... Try this:
/** Checks if a target string (haystack) starts with a specified string (needle) */
function startsWith($haystack, $needle) {
return (stripos($haystack, $needle) === 0);
}
/* Usage */
startsWith("ahi", "hi"); // Returns FALSE
startsWith("ahi", "ah"); // Returns TRUE
Please note that you need to use 3 = signs, because the function will return false when there is no match in the string.
http://php.net/manual/en/function.stripos.php
if(stripos($search_in, $search) === 0) {
echo "matched";
}
stripos($haystack, $needle) === 0
The exact function for that purpose is strncasecmp. I have no idea why everyone is so bent on stripos workarounds recently.
Albeit it needs the string length for comparison, and the result must be negated for positive matches
if (!strncasecmp($string, "search", 6)) {
The advantage is that it really only compares the first 6 characters. It does not search the whole subject and require an extra comparison afterwards. (Stupid if used as microoptimization. But it's the exact function for that task.)
function startsWithi($haystack, $needle)
{
return substr(strtolower($haystack), 0, strlen($needle))) === $needle;
}
Related
How can I preg_match exactly with that kind of search:
My value to find: #5#
My value to search: #5#;#9#
I did a simple
if (preg_match("#5#", "#5#;#9#")) { return true; } else { return false; }
And, it returns true.
The problem with that code, it's return also true if my value to compare is #51#;#55# whereas it has to be false in that case:
if (preg_match("#5#", "#51#;#55#")) { return true; } else { return false; }
Also returns true whereas I want false.
preg_match("#5#", "#51#;#55#") returns true because preg_match uses # as delimiter. In order to match #5# you have to add delimiters around the regex:
if (preg_match("/#5#/", "#51#;#55#")) { return true; } else { return false; }
This will return false.
If all you need is to find a string you know (#5#) in another string then the best way is to use function strpos(). It returns the boolean FALSE if it cannot find the string or an integer number that represents the position of the searched string into the other string.
It is faster that any preg_*() function.
$pos = strpos('#5#', '#5#;#9#');
if ($pos !== FALSE) {
echo('Found (at position '.$pos.')');
} else {
echo('Not found.');
}
You have to pay attention to the comparison operator: using $pos != FALSE is not enough because 0 == FALSE. You have to compare using === or !== to avoid this.
Using preg_match()
Your approach failed because in PHP the PCRE functions interpret the first character from the regex as a delimiter.
This means the regex in #5# is: 5. And this regex, of course, matches any 5 it finds in the string. To fix it you have to surround your regex with some delimiter (/ is usually used):
return preg_match('/#5#/', '#5#;#9#');
I am a Rubyist trying to implement some of my code in PHP and not able to get the equivalent PHP code for this particular def.Can anyone help me out.Thanks in advance.
def check_condition(str)
str =~ SOME_REGEX
end
In PHP it looks like:
function check_condition($str) {
return preg_match(SOME_REGEX, $str);
}
Unfortunately there is no regex-match operator in PHP unlike some other languages. You'll have to call a function. Follow the manual of preg_match() and the manual page about the so called perl compatible regular expresssions (preg) in general.
Something additional. After reading the manual page of preg_match you know that the method returns an integer, the number of matches found. As the method returns after the first match this can be only 0 or 1. As of the loose typing system of PHP this would be good for using it in loose comparisons like:
if(check_condition($str)) { ....
if(check_condition($str) == true) { ...
But it would not work in a strict comparison:
if(check_condition($str) === true) { ...
Therefore it would be a good idea to cast the return value of preg_match:
function check_condition($str) {
return (boolean) preg_match(SOME_REGEX, $str);
}
Update
I have thought a little bit about my last suggestion and I see a problem with this. preg_match() will return an integer if all is working fine but boolean FALSE if an error occurs. For example because of a syntax error in the regex pattern. Therefore you will be not aware of errors if you are just casting to boolean. I would use exceptions to show that an error was happening:
function check_condition($str) {
$ret = preg_match(SOME_REGEX, $str);
if($ret === FALSE) {
$error = error_get_last();
throw new Exception($error['message']);
}
return (boolean) $ret;
}
Have a look at preg_match:
if (preg_match('/regex/', $string) {
return 1;
}
Isn't it preg_match?
function check_condition($str) {
return preg_match(SOME_REGEX,$str);
}
I don't think there is an equivalent.
preg_match returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
=~however returns the position where the match starts, or nil if there is no match. Since nil is false and all numbers including zero are true, boolean operations are possible.
puts "abcdef" =~ /def/ #=> 3 # don't know how to get this from a RegExp in PHP
puts "Matches" if "abcdef"=~ /def/ #=> Matches
How to check, if a string contain multiple specific words?
I can check single words using following code:
$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad') !== false) {
echo 'true';
}
But, I want to add more words to check. Something like this:
$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad || naughty') !== false) {
echo 'true';
}
(if any of these words is found then it should return true)
But, above code does not work correctly. Any idea, what I'm doing wrong?
For this, you will need Regular Expressions and the preg_match function.
Something like:
if(preg_match('(bad|naughty)', $data) === 1) { }
The reason your attempt didn't work
Regular Expressions are parsed by the PHP regex engine. The problem with your syntax is that you used the || operator. This is not a regex operator, so it is counted as part of the string.
As correctly stated above, if it's counted as part of the string you're looking to match: 'bad || naughty' as a string, rather than an expression!
You can't do something like this:
if (strpos($data, 'bad || naughty') !== false) {
instead, you can use regex:
if(preg_match("/(bad|naughty|other)/i", $data)){
//one of these string found
}
strpos does search the exact string you pass as second parameter. If you want to check for multiple words you have to resort to different tools
regular expressions
if(preg_match("/\b(bad|naughty)\b/", $data)){
echo "Found";
}
(preg_match return 1 if there is a match in the string, 0 otherwise).
multiple str_pos calls
if (strpos($data, 'bad')!==false or strpos($data, 'naughty')!== false) {
echo "Found";
}
explode
if (count(array_intersect(explode(' ', $data),array('bad','naugthy')))) {
echo "Found";
}
The preferred solution, to me, should be the first. It is clear, maybe not so efficient due to the regex use but it does not report false positives and, for example, it will not trigger the echo if the string contains the word badmington
The regular expression can become a burden to create if it a lot of words (nothing you cannot solve with a line of php though $regex = '/\b('.join('|', $badWords).')\b/';
The second one is straight forward but can't differentiate bad from badmington.
The third split the string in words if they are separated by a space, a tab char will ruins your results.
if(preg_match('[bad|naughty]', $data) === true) { }
The above is not quite correct.
"preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred."
So it should be just:
if(preg_match('[bad|naughty]', $data)) { }
substr_count()
I want to add one more way doing it with substr_count() (above all other answers):
if (substr_count($data, 'bad') || substr_count($data, 'naughty')){
echo "Found";
}
substr_count() is counting for how many times the string appears, so when it's 0 then you know that it was not found.
I would say this way is more readable than using str_pos() (which was mentioned in one of the answers) :
if (strpos($data, 'bad')!==false || strpos($data, 'naughty')!== false) {
echo "Found";
}
You have to strpos each word. Now you are checking if there is a string that states
'bad || naughty'
which doesn't exist.
A simple solution using an array for the words to be tested and the array_reduce() function:
$words_in_data = array_reduce( array( 'bad', 'naughty' ), function ( $carry, $check ) use ( $data ) {
return ! $carry ? false !== strpos( $data, $check ) : $carry;
} );
Then you can simply use:
if( $words_in_data ){
echo 'true';
}
Here is a function that can perform this operation without using regular expressions which could be slower. Instead of passing a single string for the task, pass an array like
if (strposMultiple($data, ['bad', 'naughty']) !== false) {
//...
}
Here is the function:
function strposMultiple($haystack, $needle, $offset = 0) {
if(is_string($needle))
return strpos($haystack, $needle, $offset);
else {
$min = false;
foreach($needle as $n) {
$pos = strpos($haystack, $n, $offset);
if($min === false || $pos < $min) {
$min = $pos;
}
}
return $min;
}
}
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.