I have two strings "Mures" and "Maramures". How can I build a search function that when someone searches for Mures it will return him only the posts that contain the "Mures" word and not the one that contain the "Maramures" word. I tried strstr until now but it does now work.
You can do this with regex, and surrounding the word with \b word boundary
preg_match("~\bMures\b~",$string)
example:
$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
echo "matched";
else
echo "no match";
Use preg_match function
if (preg_match("/\bMures\b/i", $string)) {
echo "OK.";
} else {
echo "KO.";
}
How do you check the result of strstr? Try this here:
$string = 'Maramures';
$search = 'Mures';
$contains = strstr(strtolower($string), strtolower($search)) !== false;
Maybe it's a dumb solution and there's a better one. But you can add spaces to the source and destination strings at the start and finish of the strings and then search for " Mures ". Easy to implement and no need to use any other functions :)
You can do various things:
search for ' Mures ' (spaces around)
search case sensitive (so 'mures' will be found in 'Maramures' but 'Mures' won't)
use a regular expression to search in the string ( 'word boundary + Mures + word boundary') -- have a look at this too: Php find string with regex
function containsString($needle, $tag_array){
foreach($tag_array as $tag){
if(strpos($tag,$needle) !== False){
echo $tag . " contains the string " . $needle . "<br />";
} else {
echo $tag . " does not contain the string " . $needle;
}
}
}
$tag_array = ['Mures','Maramures'];
$needle = 'Mures';
containsString($needle, $tag_array);
A function like this would work... Might not be as sexy as preg_match though.
The very simple way should be similar to this.
$stirng = 'Mures';
if (preg_match("/$string/", $text)) {
// Matched
} else {
// Not matched
}
Related
I have an array
$array = ['download.png', 'download-1.png', 'download-2.png']
I want a regular expression that can match all three elements. So far I've tried and gotten something like
/('."$filename".')\-*[0-9]*$/
where $filename = 'download.png'
If it helps I am trying to use the regex in this
foreach($len as $value){
if(preg_match('/('."$filename".')\-*[0-9]*$/', $value->getValue()) ){
$array[] = $value->getValue();
var_dump( $array); echo '<br>';
}
}
help me anyone thanks in advance!
Try "/" . explode($filename, '.')[0] . "(?:-\d)?\.png/"
explode($filename, '.')[0] splits $filename into ['download', 'png'] and then gets the first element in that array, download.
(?:-\d)? is an optional (it's the ? that makes it optional) non-capturing group (that's the (?:) that matches a dash and then a number. This means that it's optional to match the -1.
From what I understand from your question, $value->getValue() is something like download-2.png. Your regex isn't matching the .png extension. I've added \.png to my regex for this.
An alternative solution without regex.
Explode on "-" if there is two items in the array it has "-" included in name.
$array = ['download.png', 'download-1.png', 'download-2.png'];
Foreach($array as $val){
$exp = explode("-", $val);
If(isset($exp[1])){
Echo "name is: " . $exp[0] . "-" . $exp[1] . "\n";
}Else{
Echo "name is: " . $exp[0] ."\n";
}
}
https://3v4l.org/5ElW3
I'm looking for the string (or strings - there might be many occurrences), between the following:
<!--## and ##-->
Example: from the input <!--##HELLO##--> I need to match HELLO.
What would be the regex?
(?<=<!--##).*?(?=##-->)
Lookaround is the only way to match only the HELLO. You can also match the entire <!--##HELLO##--> and extract captured groups as mentioned in other answers.
The regex
<!--##(.*?)##-->
Will store the text in the first group. Be sure to set the option that lets the . match newline (/s below)
For php preg this becomes
if (preg_match('/<!--##(.*?)##-->/s', $subject, $regs)) {
$result = $regs[1];
} else {
$result = "";
}
/<!--##(.*?)##-->/
Basically this is an alternative way to do this to other provided answer because I think it's simpler to use matching groups to fish out your text than to use look ahead/behind to only match what you're looking for. Tomato, Tom-ah-to.
Here is a version using preg_match_all, and an iterator that gives you each match:
$match_list = array();
if( preg_match_all('/<!--##(.*?)##-->/s', $subject, $regs) ) {
$match_list = $regs[1];
} else {
echo "Warning: No matches found in: " . $subject;
}
foreach($match_list as $i=>$v) {
echo "Match: " . $i . " : " . $v . "\n";
}
is there is some function that can take just text inside the quotes from the variable?
Just like:
$text = 'I am "pro"';
echo just_text_in_quotes($text);
I know that this function doesn't exist.. but I need something like that.
I was thinking about fnmatch("*",$text)
But this cant Echo just that text, It's just for check.
Can you please help me?
Thank you.
This function will return the first matched text between quotes (possibly an empty string).
function just_text_in_quotes($str) {
preg_match('/"(.*?)"/', $str, $matches);
return isset($matches[1]) ? $matches[1] : FALSE;
}
You could modify it to return an array of all matches, but in your example you use it within the context of echoing its returned value. Had it returned an array, all you would get is Array.
You may be better off writing a more generic function that can handle multiple occurrences and a custom delimiter.
function get_delimited($str, $delimiter='"') {
$escapedDelimiter = preg_quote($delimiter, '/');
if (preg_match_all('/' . $escapedDelimiter . '(.*?)' . $escapedDelimiter . '/s', $str, $matches)) {
return $matches[1];
}
}
This will return null if no matches were found.
preg_match is made for this
preg_match('/"(.*?)"/', $str, $quoted_string);
echo "<pre>"; print_r($quoted_string);
//return array of all quoted words in $str
This regex:
"(\w*)"
will help you as you can see here: http://rubular.com/r/3kgH7NdtLm
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 am trying to create a way of making sure that every space has at least three characters (a-zA-Z and single quotes are allowed) on each side of it. It does exactly that, however only with the first space. Not the rest of them. I tried preg_match_all() to no avail, hence my question/post to you guys.
<?PHP
function validateSpaces($str) {
if ( strpos( $str, ' ' ) !== FALSE && !preg_match( '/(([a-z\']{3,})([ ]{1})([a-z\']{3,}))/i', $str ) )
return FALSE;
return TRUE;
}
echo validateSpaces( 'Hey There' ); // Valid (correct)
echo validateSpaces( 'He There' ); // Invalid (correct)
echo validateSpaces( 'Hey Ther e' ); // Valid (incorrect)
?>
As you can see, the first two examples are working like they should, but the second one validates although the second space only has one character on the right side of it. Which is not what I want.
Any help or attempt to help is greatly appreciated!
Thank you in advance,
Chris.
Last modification, will macth only if we have ony one space (trim string before trying to match it):
^([a-z']{3,} ?)+$
You could explode the string on spaces and check the array's contents.
Not complete solution:
$temb=explode(' ', $str);
$valid=true;
foreach ($temb as $tt) {
if (strlen($tt)<3 || !{a preg_match for the right characters in $tt}) {
$valid=false;
break;
}
}
Use preg_match_all() rather than preg_match(), and compare the number of results with a substr_count($str,' ') to see that every space matches your regexp criteria
How about this - you could combine the patterns into one if performance is an issue; I find more than one level of conditional logic difficult to read:
function validate( $value )
{
$ptn_a = '/(^| )[A-Za-z\']{0,2} /';
$ptn_b = '/ [A-Za-z\']{0,2}($| )/';
if ( preg_match( $ptn_a, $value ) )
return false;
if ( preg_match( $ptn_b, $value ) )
return false;
return true;
}
var_dump( validate('Hey There') );
var_dump( validate('He There') );
var_dump( validate('Hey Ther e') );
function validate($string = '')
{
$regexp = '/([^\w]|^)([\w]{1,2})([^\w]|$)/';
if (strlen(trim($string)) && !preg_match($regexp, $string)) {
return 'TRUE';
}
return 'FALSE';
}
print validate(' ');
print "\n";
print validate('Hey There');
print "\n";
print validate('He There');
print "\n";
print validate('Hey ');
print "\n";
print validate('Hey Ther e');
print "\n";
print validate('Hey Th ere');
This can also help.