is there a way to find a word in a sentence using PHP? We have a form and in the subject line we want to redirect someone if they use the words delivery, deliver, or delivered. Can this be done and how would it be? thank you for any help on this subject.
This should do it:
if ( preg_match('/deliver(?:y|ed)?/i', $subject) )
{
// Redirect
}
You can use the strpos function to search for a string inside another string. If the string is not found false will be returned, and you know that your string was not found.
another method:
if (stristr($sentence,"deliver")) {
header('location: somepage.php');
}
But I would use preg_match as expressed before.
One method of many:
if (preg_match('/deliver(y|ed)?/', $string)) {
// yes, $string contained 'deliver', 'delivery' or 'delivered'
}
Here:
<?php
if (strpos($string, "deliver")) {
header("Location: somepage.php");
}
?>
to extract all words, simple explode the string using a whitespace characters
to check a particular word either use the simple strpos() function or a regular expression pattern matching
preg_match("/(?:^|\s+)deliver(y|ed)?(?:$|\s+)/i")
The above expression checks whitespace character or beginning of string, similary whitespace character or end of string
Related
What's the best way to search a string in php and find a case insensitive match?
For example:
$SearchString = "This is a test";
From this string, I want to find the word test, or TEST or Test.
Thanks!
EDIT
I should also mention that I want to search the string and if it contains any of the words in my blacklist array, stop processing it. So an exact match of "Test" is important, however, the case is not
If you want to find word, and want to forbid "FU" but not "fun", you can use regularexpresions whit \b, where \b marks the starts and ends of words,
so if you search for "\bfu\b" if not going to match "fun",
if you add a "i" behind the delimiter, its search case insesitive,
if you got a list of word like "fu" "foo" "bar" your pattern can look like:
"#\b(fu|foo|bar)\b#i", or you can use a variable:
if(preg_match("#\b{$needle}\b#i", $haystack))
{
return FALSE;
}
Edit, added multiword example whit char escaping as requested in comments:
/* load the list somewhere */
$stopWords = array( "word1", "word2" );
/* escape special characters */
foreach($stopWords as $row_nr => $current_word)
{
$stopWords[$row_nr] = addcslashes($current_word, '[\^$.|?*+()');
}
/* create a pattern of all words (using # insted of # as # can be used in urls) */
$pattern = "#\b(" . implode('|', $stopWords) . ")\b#";
/* execute the search */
if(!preg_match($pattern, $images))
{
/* no stop words */
}
You can do one of a few things, but I tend to use one of these:
You can use stripos()
if (stripos($searchString,'test') !== FALSE) {
echo 'I found it!';
}
You can convert the string to one specific case, and search it with strpos()
if (strpos(strtolower($searchString),'test') !== FALSE) {
echo 'I found it!';
}
I do both and have no preference - one may be more efficient than the other (I suspect the first is better) but I don't actually know.
As a couple of more horrible examples, you could:
Use a regex with the i modifier
Do if (count(explode('test',strtolower($searchString))) > 1)
stripos, I would assume. Presumably it stops searching when it finds a match, and I guess internally it converts to lower (or upper) case, so that's about as good as you'll get.
http://us3.php.net/manual/en/function.preg-match.php
Depends if you want to just match
In this case you would do:
$SearchString= "This is a test";
$pattern = '/[Test|TEST]/';
preg_match($pattern, $SearchString);
I wasn't reading the question properly. As stated in other answers, stripos or a preg_match function will do exactly what you're looking for.
I originally offered the stristr function as an answer, but you actually should NOT use this if you're just looking to find a string within another string, as it returns the rest of the string in addition to the search parameter.
I am trying to validate form input data using PHP's preg_match function. I am a little confused of how to use it. If I want to validate say an alphanumeric string, I would use ^[0-9a-zA-Z ]+$ as the first parameter and the string we're validating as the second one. But how would I use preg_match to tell if it's valid or not? Would I do this:
if(preg_match("^[0-9a-zA-Z ]+$", $_POST['display_name'])){
"String is valid";
} else {
"String is not valid";
}
Or the other way around? I am currently using the if not preg_match if statement but it's returning false for some reason... I know this is probably an easy answer, but I cannot figure this out.
FALSE return from a preg_match indicates an error
you need to delimit your regex (see the leading and trailing / you can use other characters too
if (preg_match("/^[0-9a-zA-Z ]+$/", $_POST['display_name'])) {
You need add the delimiters of your pattern, like this:
preg_match("/^[0-9a-zA-Z ]+$/", $_POST['display_name'])
I am using php and I am using regular expressions to try to detect a quotation.
I would like for it to find matches only if it finds a quotation in the string
HELLO
Shouldnt find any matches
"HELLO"
Should find a match
"HELLO
Still should find a match
The regular expression is just the quote character.
echo preg_match('/"/', $string);
That will return 0 for HELLO, 1 for "HELLO" and 1 for "HELLO
You could use a regular expression with preg_match, which checks for any double-quote in $thestring:
if(preg_match('"', $thestring)) { ... }
But it may be faster to use the strpos function instead:
if(strpos($thestring, '"') !== false) { ... }
The code inside the if statements will only be executed if a double-quote is found. My code examples won't return which text was quoted, although you can certainly do that with a few changes.
Use "(.*?)(\n|\r|$|").
Example:
http://img221.imageshack.us/img221/2994/screenshot2z0.png
EDIT: from your comments I understand that you don't need this; what you need is Colin O'Dell's answer (namely the strpos function). Still, I'm leaving this here in case anyone else needs it.
Not so difficult, IMHO :)
I guess you are just trying to determine whether there is a quote in the given string or not, right? So then it can by done by
preg_match('/"/',$string)
or more efficiently by
strpos($string,'"') || $string == '"'
["]*HELLO["]*
will match HELLO with or without quotes on either side.
Or you can use
"{0,1}HELLO"{0,1}
Use (trim($string, '"') !== $string)
Or (trim($string, '"\'') !== $string) for quotation or single quote
In PHP, how do I check if a String contains only letters? I want to write an if statement that will return false if there is (white space, number, symbol) or anything else other than a-z and A-Z.
My string must contain ONLY letters.
I thought I could do it this way, but I'm doing it wrong:
if( ereg("[a-zA-Z]+", $myString))
return true;
else
return false;
How do I find out if myString contains only letters?
Yeah this works fine. Thanks
if(myString.matches("^[a-zA-Z]+$"))
Never heard of ereg, but I'd guess that it will match on substrings.
In that case, you want to include anchors on either end of your regexp so as to force a match on the whole string:
"^[a-zA-Z]+$"
Also, you could simplify your function to read
return ereg("^[a-zA-Z]+$", $myString);
because the if to return true or false from what's already a boolean is redundant.
Alternatively, you could match on any character that's not a letter, and return the complement of the result:
return !ereg("[^a-zA-Z]", $myString);
Note the ^ at the beginning of the character set, which inverts it. Also note that you no longer need the + after it, as a single "bad" character will cause a match.
Finally... this advice is for Java because you have a Java tag on your question. But the $ in $myString makes it look like you're dealing with, maybe Perl or PHP? Some clarification might help.
Your code looks like PHP. It would return true if the string has a letter in it. To make sure the string has only letters you need to use the start and end anchors:
In Java you can make use of the matches method of the String class:
boolean hasOnlyLetters(String str) {
return str.matches("^[a-zA-Z]+$");
}
In PHP the function ereg is deprecated now. You need to use the preg_match as replacement. The PHP equivalent of the above function is:
function hasOnlyLetters($str) {
return preg_match('/^[a-z]+$/i',$str);
}
I'm going to be different and use Character.isLetter definition of what is a letter.
if (myString.matches("\\p{javaLetter}*"))
Note that this matches more than just [A-Za-z]*.
A character is considered to be a letter if its general category type, provided by Character.getType(ch), is any of the following: UPPERCASE_LETTER, LOWERCASE_LETTER, TITLECASE_LETTER, MODIFIER_LETTER, OTHER_LETTER
Not all letters have case. Many characters are letters but are neither uppercase nor lowercase nor titlecase.
The \p{javaXXX} character classes is defined in Pattern API.
Alternatively, try checking if it contains anything other than letters: [^A-Za-z]
The easiest way to do a "is ALL characters of a given type" is to check if ANY character is NOT of the type.
So if \W denotes a non-character, then just check for one of those.
I want to check whether the search keyword 'cli' or 'ent' or 'cl' word exists in the string 'client' and case insensitive. I used the preg_match function with the pattern '\bclient\b'. but it is not showing the correct result. Match not found error getting.
Please anyone help
Thanks
I wouldn't use regular expressions for this, it's extra overhead and complexity where a regular string function would suffice. Why not go with stripos() instead?
$str = 'client';
$terms = array('cli','ent','cl');
foreach($terms as $t) {
if (stripos($str,$t) !== false) {
echo "$t exists in $str";
break;
}
}
Try the pattern /cli?|ent/
Explanation:
cli matches the first part. The i? makes the i optional in the search.
| means or, and that matches cli, or ent.
\b is word boundary, It would not match cli in client, you need to remove \b