How to check specyfic url_path in preg_match - php

How can I check if specific path match to pattern.
Example:
I have a path with one or more unknown variable
$pathPattern = 'user/?/stats';
And let say I received this path
$receivedPath = 'user/12/stats'
So, how can I check if that received path match to my pattern?
I tried to do something like below but didn't work.
$pathPattern = 'user/?/stats';
$receivedPath = 'user/12/stats';
$pathPatternReg = str_replace('?','.*',$pathPattern);
echo preg_match('/$pathPatternReg/', $receivedPath);
Thank you.

Regex should be something like this for a unknown user\/[0-9]+\/stats
And Could be used as such;
if(preg_match("user\/[0-9]+\/stats",$variable)) { .... }

As stated by Tom, you possibly have to escape the '/' characters with a '\'.
You only want to match one specific part of your total query string, the number in the center. Most regex interpreters provide this functionality in form of round brackets, like this:
$pattern = "user\/([0-9]+)\/stats";
Notice the round brackets around the [0-9]+ : it tells preg_match to store this part of the matched pattern in the $matches array.
So, your code could look like this:
$subject = "user/12/stats";
$pattern = "user\/([0-9]+)\/stats";
$matches = array();
if( preg_match($pattern, $subject, $matches) ){
// there was a match
// The $matches array now looks like this:
// { "user/12/stats", "12" }
// { <whole matched string>, <string in first parenthesis>, .... }
$user_id = $matches[1]
...
}
(not tested)
See also here: https://secure.php.net/manual/en/function.preg-match.php

Thank you booth.
This is a solution:
$pathPattern = 'user/?/stats';
$receivedPath = 'user/12/stats';
$pathPatternReg = str_replace(['/','?'],['\/','.*'],$pathPattern);
$pattern = "/^$uri/";
echo preg_match($pattern, $receivedPath);

Related

REGEX match two patterns between specific characters

I know the title may be a little vague but I wasnt sure how to formulate it. I have a string that contains text that looks something like this:
$data["key1"] = "value1";
$data["key2"] = "value2";
$data["key3"] = "value3";
$data["key4"] = "value4";
I would like to match everything after $data[" and ]" and everything in between = " and "; in the same match, so for example the results would be
Match 1 = {key1, value1}
Match 2 = {key2, value2}
Match 3 = {key3, value3}
Match 4 = {key4, value4}
So far I have been able to match the values with
/(?<=]\s=\s\")(.*?)(?=\s*\"\;)/
but I would also need the first part in the result as well and I'm not sure how to do so.
Also, is there a way to have it match if there is (or isn't) white spaces between characters?
for example
$data["key1"]= "value1";
$data["key2"]="value2";
$data["key3"] ="value3";
$data["key4"] ="value4" ;
Would also all match the same thing?
Try using preg_match_all:
$input = '$data["key1"] = "value1";';
preg_match_all('/\$\w+\["(.*?)"\]\s*=\s*"(.*?)";/', $input, $matches);
echo "Match = {" . $matches[1][0] . ", " . $matches[2][0] . "}";
This prints:
Match = {key1, value1}
You can try the following for each line. Basically you just need to search for each pair of quotes in each line should do the work.
// $output_array is an array which the first index is your key and second is the value
// for example, array( "key1", "value1")
$input_lines = '$data["key1"] = "value1"';
preg_match_all('/\"\w+\"/', $input_lines, $output_array);

PHP extract one part of a string

I have to extract the email from the following string:
$string = 'other_text_here to=<my.email#domain.fr> other_text_here <my.email#domain.fr> other_text_here';
The server send me logs and there i have this kind of format, how can i get the email into a variable without "to=<" and ">"?
Update: I've updated the question, seems like that email can be found many times in the string and the regular expresion won't work well with it.
You can try with a more restrictive Regex.
$string = 'other_text_here to=<my.email#domain.fr> other_text_here';
preg_match('/to=<([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})>/i', $string, $matches);
echo $matches[1];
Simple regular expression should be able to do it:
$string = 'other_text_here to=<my.email#domain.fr> other_text_here';
preg_match( "/\<(.*)\>/", $string, $r );
$email = $r[1];
When you echo $email, you get "my.email#domain.fr"
Try this:
<?php
$str = "The day is <tag> beautiful </tag> isn't it? ";
preg_match("'<tag>(.*?)</tag>'si", $str, $match);
$output = array_pop($match);
echo $output;
?>
output:
beautiful
Regular expression would be easy if you are certain the < and > aren't used anywhere else in the string:
if (preg_match_all('/<(.*?)>/', $string, $emails)) {
array_shift($emails); // Take the first match (the whole string) off the array
}
// $emails is now an array of emails if any exist in the string
The parentheses tell it to capture for the $matches array. The .* picks up any characters and the ? tells it to not be greedy, so the > isn't picked up with it.

This script won't find Absolute Urls

in the code below, it is supposed to scan links and index them in the array [links]. but for some reason, they won't index.
I am starting to think if my regex code is wrong, how can i improve it. Also is it my file_get_contents command? Is it used correctly?
$links = Array();
$URL = 'http://www.theqlick.com'; // change it for urls to grab
// grabs the urls from URL
$file = file_get_contents($URL);
$abs_url = preg_match_all("'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$^'", $file, $link);
if (!empty($abs_url)) {
$links[] = $abs_url;
}
In your preg_match_all you are saving into $link not $links.
preg_match_all Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred (c) php.net
preg_match_all("'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$^'", $file, $matches);
if (!empty($matches)
$links = $matches;
Your regex is wrong. You have a head anchor ^ at the end of the pattern adjacent to a tail match $. I don't think the anchors really aren't needed. Additionally, your variable you are storing matches in $link (no s). Plus your pattern delimiter appears to be the ' character. Was that intentional? It would fortunately work, but I'm guessing you didn't intend for that?
Try this:
$matchCount = preg_match_all("/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/", $file, $matches);
if ($matchCount)
{
foreach ($matches as $match)
{
$links[] = $match[0];
}
}
Read up on PHP regular expressions.

regex pattern to match a url in php

i need help with this regex pattern. I have tried many different patterns but none return anything. I always get an empty array. The following patterns return no results.
//test 1
$regex = '/linkDestUrl = \'(.*)\'/';
//test 2
$regex = '#^(?:\s)*(linkDestUrl = \'(.*)\');#mi';
to match this
linkDestUrl = 'http://www.google.com';
if its that simple, this should work:
$search = "linkDestUrl = 'http://www.google.com';";
preg_match_all("/linkDestUrl = '(.*)';/im", $search, $result);
var_dump($result[1]);
Try it out on http://regex.larsolavtorvik.com/
You can use a site like http://gskinner.com/RegExr/ to test your reg exp

PHP - strip URL to get tag name

I need to strip a URL using PHP to add a class to a link if it matches.
The URL would look like this:
http://domain.com/tag/tagname/
How can I strip the URL so I'm only left with "tagname"?
So basically it takes out the final "/" and the start "http://domain.com/tag/"
For your URL
http://domain.com/tag/tagname/
The PHP function to get "tagname" is called basename():
echo basename('http://domain.com/tag/tagname/'); # tagname
combine some substring and some position finding after you take the last character off the string. use substr and pass in the index of the last '/' in your URL, assuming you remove the trailing '/' first.
As an alternative to the substring based answers, you could also use a regular expression, using preg_split to split the string:
<?php
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
?>
(The reason for the -2 is because due to the ending /, the final element of the array will be a blank entry.)
And as an alternate to that, you could also use preg_match_all:
<?php
$ptn = "/[a-z]+/";
$str = "http://domain.com/tag/tagname/";
preg_match_all($ptn, $str, $matches);
$tagname = $matches[count($matches)-1];
echo($tagname);
?>
Many thanks to all, this code works for me:
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);

Categories