PHP regular expression - php

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

Related

Preg_grep() Regex pattern is not working as expected

I have the following code and I'm trying to achieve an effect like this
-Remove the "-" and number from the end of the string.
-Then check if the value is matching or not.
Here's my PHP code
$usernames= array("microsoft-2","google-1","google");
$value='google';
$input = preg_quote($value, '~');
$result = preg_grep('~' . $value . '~', $usernames);
echo '<pre>';
print_r($result);
//Array
(
[1] => google-1
[2] => google
)
The above results are fine but the problem is If I set value as "goog" it returns the same result while I'm expecting it to return an empty erray.
The usernames are coming from database and can be a large number.
In short it should return an remove the dash and number at the end and afterwards it should check if the values are same or not. If yes, then push in results otherwise not.
Any help would be appreciated ! Many Thanks
Add word break \b
$usernames= array("microsoft-2","google-1","google");
$value='goog';
$input = preg_quote($value, '~');
$result = preg_grep('~' . $value . '\b~', $usernames);
echo '<pre>';
print_r($result);
Output
array()
Sandbox
You can even add one to each side $result = preg_grep('~\b' . $value . '\b~', $usernames); in this case goog you only need the right one.

Return part of string

I have an array with strings like:
209#ext-local : SIP/209 State:Idle Watchers 2
208#ext-local : SIP/208 State:Unavailable Watchers 1
How can I echo the state for example Idle or Unavailable?
Thanks.
Using regex it will match any string containing letters and numbers.
$string = '209#ext-local : SIP/209 State:Idle Watchers 2';
preg_match("/State\:([A-Za-z0-9]+)/", $string, $results);
echo $results[1]; // Idle
strpos will search the string to see if it is contains the characters in that exact order.
strpos will not always work if the word idle or unavailable has the possibility to show up in any other way in the string.
You can use the php explode and parse the sting into an array of strings.
exp.
$string = "209#ext-local : SIP/209 State:Idle Watchers 2";
$string = explode(':', $string);
will give you ['209#ext-local ',' SIP/209 State','Idle Watchers 2']. Then if you explode the 3rd entry my ' ' you would get your answer.
$answer = explide(' ', $string[2]);
echo $answer[0];
Assuming your strings are all the same format, you can try splitting the string down using explode(), which returns an array of string, separated by a provided delimiter, like
foreach ($yourStrings as $s) {
$colonSplit = explode(":", $stringToSplit);
$nextStringToSplit = $colonSplit[2];
$spaceSplit = explode(" ", $nextStringToSplit);
$status = $spaceSplit[0];
echo $status;
}
May not be elegant but it should work.
Quick (and dirty) way. Assuming your array contains the full elements you listed above, the array element values do NOT contain 'idle' or 'unavailable' in any other capacity other than what you listed, and you just want to echo out the value and "is idle" or "is unavailable":
//$a being your array containing the values you listed above
foreach ($a as $status) {
if (strpos($status, "Idle") == true)
echo $status . " is idle";
elseif (strpos($status, "Unavailable") == true)
echo "$status" . " is unavailable";
}

Find exact string inside a string

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
}

How to find all matches of text between two fixed tokens with PHP regex?

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";
}

PHP Divide variable into two different variables

I have this variable : $lang['_city']
I need to divide it in two portions.
One portion will be $key == lang and second portion will be $ind == _city
I think I can do it with some sort of regexp but I am not good with it.
Can you help me?
P.S. The above example is only a sample. I need an abstract function that will do it with any passed variable.. So for example, get whatever is before [ and cut the $, and then get whatever is inside [' '].. I know the logic but not the way to do it :)
Also the new values will have to be assigned each one to a variable as explained before.
Thanks
$string = "\$foo['bar']";
preg_match('~^\$(?\'key\'[^\[]+)\[\'(?\'ind\'[^\']+)~', $string, $matches);
var_dump($matches['key'], $matches['ind']);
http://ideone.com/XaopX
Regexp for preg_match would be: ~^\$([^\[]+)\[\s*("[^"]+"|'[^']+')\s*\]$~ (you'll need to escape ' or " when moving to string).
Than:
$key = $match[1];
$ind = substr( $match[2], 1, -1);
You do not even need regexp here :)
$str = "\$lang['city']";
$tmp = explode('[', $str);
$key = ltrim($tmp[0], '$');
$ind = trim($tmp[1], ']\'"');
echo $key . '=>' . $ind;
Starting from PHP 5.4 you could do it even shorter
$str = "\$lang['city']";
$key = ltrim(explode('[', $str)[0], '$');
$ind = trim(explode('[', $str)[1], ']\'"');
echo $key . '=>' . $ind;

Categories