Extract Key from URL with Preg_Match in PHP - php

I haves this URL
https://test.com/file/5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
I need to create with preg_mach this condition:
$match[0]=5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
$match[1]=5gdxyYpb
$match[2]=_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
I try difference pattern the mos closed was this one. e\/(.*?)\#(.*).
Please any recommendation. (If necessary in Preg_Match).
Thank you,

You might use 2 capturing groups and make use of \K to not match the first part of the url to get the desired matches.
https?://.*/\K([^#\s]+)#(\S+)
https?:// Match the protocol with optional s, then ://
.*/ Match until the last occurrence of /
\K Forget what is matched until here
([^#\s]+) Capture group 1, match 1+ occurrences of any char except a # or whitespace char
# Match the #
(\S+) Capture group 2, match 1+ occurrences of a non whitespace char
Regex demo | Php demo
$url = "https://test.com/file/5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE";
$pattern = "~https?://.*/\K([^#]+)#(.*)~";
$res = preg_match($pattern, $url, $matches);
print_r($matches);
Output
Array
(
[0] => 5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
[1] => 5gdxyYpb
[2] => _FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
)

Related

I need preg_match_all() pattern in getting string inside square bracket tags PHP

I want to parse a string to get the value inside a square bracket tag:
[vc_column_text][/vc_column_text]
I am using preg_match_all() in PHP
$string = '[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text css=".vc_custom_1576642149231{margin-bottom: 0px !important;}"]This is the string I want to fetch[/vc_column_text][/vc_column][/vc_row]`;
I tried this:
preg_match_all("'[vc_column_text(.*?)](.*?)[/vc_column_text]'", $string, $matches);
But this only returns an array of 2-3 characters:
A help will be very much appreciated :)
If you want to match only the sentence, you could use first match [vc_column_text followed by any char except [ or ] and then match the closing ]
Then match 0+ occurrences of a whitespace char and capture 1 or more occurrences of any char except a whitespace in group 1.
\[vc_column_text[^][]*\]\s*(.+?)\[/vc_column_text]
Explanation
\[vc_column_text Match [vc_column_text
[^][]*\] Match [, then 0+ occurrences of any char except [ or ] and match ]
\s* Match 0+ whitespace chars
(.+?) Capture group 1, match any char 1+ times non greedy
\[/vc_column_text] Match [/vc_column_text]
Regex demo | Php demo
Example code
$string = '[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text css=".vc_custom_1576642149231{margin-bottom: 0px !important;}"]This is the string I want to fetch[/vc_column_text][/vc_column][/vc_row]';
preg_match_all("~\[vc_column_text[^][]*\]\s*(.+?)\[/vc_column_text]~", $string, $matches);
print_r($matches[1]);
Output
Array
(
[0] => This is the string I want to fetch
)

regex expected value in a postion depends on a random value in another position

I need regex to find all shortcode tag pairs that look like this [sc1-g-data]b[/sc1-g-data] but the number next to the sc can vary but they must match.
So something like this won't work \[sc(.*?)\-((.|\n)*?)\[\/sc(.*?)\- as this matches unmatching tag pairs like this which i don't want [sc1-g-data]b[/sc2-g-data]
so the expected number in the second tag depends on a random number in the first tag
You may use a regex like:
\[(sc\d*-[^\]\[]*)\]([\s\S]*?)\[\/\1\]
See the regex demo
\[ - a [ char
(sc\d*-[^\]\[]*) - Capturing group 1: sc, 0+ digits, -, and then 0+ chars other than ] and [
\] - a ] char
([\s\S]*?) - Capturing group 2: any 0+ chars, as few as possible
\[\/ - a [/ string
\1 - the same text stored in Group 1
\] - a ] char
See the regex graph:
PHP demo:
$pattern = '~\[(sc\d*-[^][]*)](.*?)\[/\1]~s';
$string = '[sc1-g-data]a[/sc1-g-data] ';
if (preg_match($pattern, $string, $matches)) {
print_r($matches);
}
Mind the use of a single quoted string literal, if you use a double quoted one you will need to use \\1, not \1 as '\1' != "\1" in PHP.
Output:
Array
(
[0] => [sc1-g-data]a[/sc1-g-data]
[1] => sc1-g-data
[2] => a
)
If your tags are just anything between brackets [blah][/blah] you can use:
\[(.*?)\].*?\[\/\1\]

Regex of number inside brackets

I need to get the float number inside brackets..
I tried this '([0-9]*[.])?[0-9]+' but it returns the first number like 6 in the first example.
Also I tried this
'/\((\d+)\)/'
but it returns 0.
Please note that I need the extracted number either int or float.
Can u plz help
As you need to match bracket also, You need to add () in regular expression:
$str = 'Serving size 6 pieces (40)';
$str1 = 'Per bar (41.5)';
preg_match('#\(([0-9]*[.]?[0-9]+)\)#', $str, $matches);
print_r($matches);
preg_match('#\(([0-9]*[.]?[0-9]+)\)#', $str1, $matches);
print_r($matches);
Output:
Array
(
[0] => (40)
[1] => 40
)
Array
(
[0] => (41.5)
[1] => 41.5
)
DEMO
You could escape brackets:
$str = 'Serving size 6 pieces (41.5)';
if (preg_match('~\((\d+.?\d*)\)~', $str, $matches)) {
print_r($matches);
}
Outputs:
Array
(
[0] => (41.5)
[1] => 41.5
)
Regex:
\( # open bracket
( # capture group
\d+ # one or more numbers
.? # optional dot
\d* # optional numbers
) # end capture group
\) # close bracket
You could also use this to get only one digit after the dot:
'~\((\d+.?\d?)\)~'
You need to escape the brackets
preg_match('/\((\d+(?:\.\d+)?)\)/', $search, $matches);
explanation
\( escaped bracket to look for
( open subpattern
\d a number
+ one or more occurance of the character mentioned
( open Group
?: dont save data in a subpattern
\. escaped Point
\d a number
+ one or more occurance of the character mentioned
) close Group
? one or no occurance of the Group mentioned
) close subpattern
\) escaped closingbracket to look for
matches numbers like
1,
1.1,
11,
11.11,
111,
111.111 but NOT .1, .
https://regex101.com/r/ei7bIM/1
You could match an opening parenthesis, use \K to reset the starting point of the reported match and then match your value:
\(\K\d+(?:\.\d+)?(?=\))
That would match:
\( Match (
\K Reset the starting point of the reported match
\d+ Match one or more digits
(?: Non capturing group
\.\d+ Match a dot and one or more digits
)? Close non capturing group and make it optional
(?= Positive lookahead that asserts what follows is
\) Match )
) Close posive lookahead
Demo php

Match regex pattern that isn't within a bbcode tag

I am attempting to create a regex patten that will match words in a string that begin with #
Regex that solves this initial problem is '~(#\w+)~'
A second requirement of the code is that it must also ignore any matches that occur within [quote] and [/quote] tags
A couple of attempts that have failed are:
(?:[0-9]+|~(#\w+)~)(?![0-9a-z]*\[\/[a-z]+\])
/[quote[\s\]][\s\S]*?\/quote](*SKIP)(*F)|~(#\w+)~/i
Example: the following string should have an array output as displayed:
$results = [];
$string = "#friends #john [quote]#and #jane[/quote] #doe";
//run regex match
preg_match_all('regex', $string, $results);
//dump results
var_dump($results[1]);
//results: array consisting of:
[1]=>"#friends"
[2]=>"#john"
[3]=>"#doe
You may use the following regex (based on another related question):
'~(\[quote](?:(?1)|.)*?\[/quote])(*SKIP)(*F)|#\w+~s'
See the regex demo. The regex accounts for nested [quote] tags.
Details
(\[quote](?:(?1)|.)*?\[/quote])(*SKIP)(*F) - matches the pattern inside capturing parentheses and then (*SKIP)(*F) make the regex engine omit the matched text:
\[quote] - a literal [quote] string
(?:(?1)|.)*? - any 0+ (but as few as possible) occurrences of the whole Group 1 pattern ((?1)) or any char (.)
\[/quote] - a literal [/quote] string
| - or
#\w+ - a # followed with 1+ word chars.
PHP demo:
$results = [];
$string = "#friends #john [quote]#and #jane[/quote] #doe";
$rx = '~(\[quote\](?:(?1)|.)*?\[/quote])(*SKIP)(*F)|#\w+~s';
preg_match_all($rx, $string, $results);
print_r($results[0]);
// => Array ( [0] => #friends [1] => #john [2] => #doe )

Wordpress get the parameter of the first shortcode in the content

I am writing a script to find the first occurrence of the following shortcode in content and then get the url parameter of the shortcode.
the shortcode looks like this
[soundcloud url="http://api.soundcloud.com/tracks/106046968"]
and what i have currently done is
$pattern = get_shortcode_regex();
$matches = array();
preg_match("/$pattern/s", get_the_content(), $matches);
print_r($matches);
and the result looks like
Array (
[0] => [soundcloud url="http://api.soundcloud.com/tracks/106046968"]
[1] =>
[2] => soundcloud
[3] => url="http://api.soundcloud.com/tracks/106046968"
[4] =>
[5] =>
[6] =>
)
Here is the string from which i need the url of the parameter of the shortcode
$html = 'Our good homies DJ Skeet Skeet aka Yung Skeeter & Wax Motif have teamed up to do a colossal 2-track EP and we\'re getting the exclusive sneak-premiere of the EP\'s diabolical techno b-side called "Hush Hush" before its released tomorrow on Dim Mak Records!
[soundcloud url="http://api.soundcloud.com/tracks/104477594"]
Wax Motif have teamed up to do a colossal 2-track EP and we\'re getting the exclusive sneak-premiere of the EP\'s diabolical techno b-side called "Hush Hush" before its released tomorrow on Dim Mak Records!
';
I guess this is not the best way to do it. If can guide me how we can do this then it would be great. Basically i want to extract the first occurrence of soundcloud url from the content.
So here's what I came up with:
preg_match('~\[soundcloud\s+url\s*=\s*("|\')(?<url>.*?)\1\s*\]~i', $input, $m); // match
print_r($m); // print matches (groups) ...
$url = isset($m['url']) ? $m['url']:''; // if the url doesn't exist then return empty string
echo 'The url is : ' . $url; // Just some output
Let's explain the regex:
~ # set ~ as delimiter
\[soundcloud # match [soundcloud
\s+ # match a whitespace 1 or more times
url # match url
\s* # match a whitespace 0 or more times
= # match =
\s* # match a whitespace 0 or more times
("|\') # match either a double quote or a single quote and put it in group 1
(?<url>.*?) # match everything ungreedy until group 1 is found and put it in a named group "url"
\1 # match what was matched in group 1
\s* # match a whitespace 0 or more times
\] # match ]
~ # delimiter (end expression)
i # set the i modifier, which means match case-insensitive
Online PHP demo
Online regex demo

Categories