How to make regex with this format "image(numeric, string)"? - php

i want to make regex to detect this format image(numeric, string). ex: image(100, 'test').
i have tried this one, but just detect the image(numeric)
/image\((\d+)\)/
Any help with second parameter and the ,?
Also how i can get the second parameter?

You can try the following pattern:
/image\(\d+,\s*'.+?'\)/
I removed the capture group since it would be not needed if using the regex for validation only.
Demo
If you want to capture the number and text, then use capture groups:
$input = "code image(123, 'meh') more code";
if (preg_match("/image\((\d+),\s*'(.+?)'\)/", $input, $m)) {
echo "match";
}
$number = $m[1];
$text = $m[2];

Try this:
image\((\d+), '(.+?)'\)
The . matches anything and the rest is pretty much self-explanatory. Group 1 is your number, group 2 is the string.

You can try this one:
image\(\s*\d+\s*\,\s*'.*'\s*\)

Related

Regex find between words, but don't return the search words

I'm trying to grab Subject from an email.
This works:
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
But returns like this:
"Subject:This is my subject!Date:"
I want just This is my subject! according to what I've read, that's what I should be getting. What am I missing?
You can use subjects[1][0] to access the value as
$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
print_r($subjects[1][0]);
Ideone Demo
When you use preg_match_all, $subjects is an array of array containing all the possible matches, but the first match i.e. $subjects[0][0] is always the whole string matched irrespective of any capturing group
Try to output just the capturing group $subjects[1][0], i.e.:
$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
$theSubject = $subjects[1][0];
echo $theSubject;
//This is my subject!
DEMO
http://ideone.com/ynyidy
Another solution other than rock321987's comment is to look look-around assertions like this.
Regex: (?<=Subject:)(.*?)(?=Date:)
Php Code:
<?php
$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/(?<=Subject:)(.*?)(?=Date:)/', $theEmail, $subjects);
print_r($subjects[0]);
?>
Regex101 Demo
Ideone Demo

Regex only for specific domain name in URL

As much as I've tried I can't seem to find the correct regex to locate what I'm after here.
I only want to select the first instance of the url that matches the domain www.myweb.com from the following...
Some text https://www.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr
I need to completely ignore the second url www.adifferentsite.com and only work with the first one that matches www.myweb.com, ignoring any other possible instances of www.myweb.com
Once the first matching domain is discovered I need to store the rest of the url that comes after it...
page/cat/323123442321-rghe432
...into a new variable $newvar, so...
$newvar = 'page/cat/323123442321-rghe432';
I'm trying :
return preg_replace_callback( '/http://www.myweb.com/\/[0-9a-zA-Z]+/', array( __CLASS__, 'my_callback' ), $newvar );
I've read tons of documents on how to detect url's but can't find anything about detecting a specific url.
I really can't grasp how to formulate regex so this formula is incorrect. Any help would be greatly appreciated.
EDIT Edited the question to be a bit more specific and hopefully a bit easier to resolve.
You can use a preg_replace_callback and pass an array into the anonymous function (or just your custom callback function) to fill it with all the necessary URL parts.
Here is a demo:
$rests = array();
$re = '~\b(https?://)www\.myweb\.com/(\S+)~';
$str = "Some text https://www.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr";
echo $result = preg_replace_callback($re, function ($m) use (&$rests) {
array_push($rests, $m[2]);
return $m[1] . "embed.myweb.com/" . $m[2];
}, $str) . PHP_EOL;
print_r($rests);
Results:
Some text https://embed.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr
Array
(
[0] => page/cat/323123442321-rghe432
)
A couple of words:
'~\b(https?://)www\.myweb\.com/(\S+)~' has ~ as a regex delimiter, so you do not have to escape /
It is declared with a single-quoted literal, so you do not have to use double-escaping for \\S
It matches and captures into capturing groups 2 substrings: \b(https?://) (that matches a whole word http or https followed by ://) and (\S+) (that matches 1 or more non-whitespace characters). These capturing groups are marked with (...) in the pattern and can be accessed via $matches[n] where n is the id of the capturing group.
UPDATE
If you only need to replace the first occurrence of the URL, pass the limit argument to the preg_replace_callback:
$rest = "";
$re = '~\b(https?://)www\.myweb\.com/(\S+\b)~';
$str = "Some text https://www.myweb.com/page/cat/323123442321-rghe432, another http://www.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr";
echo $result = preg_replace_callback($re, function ($m) use (&$rest) {
$rest = $m[2];
return $m[1] . "embed.myweb.com/" . $m[2];
}, $str, 1) . PHP_EOL;
//-LIMIT ^ - HERE -
echo $rest;
See another IDEONE demo

Check number ID with Preg_match

i've a little problem.
I want to check the numer of post like this:
http://xxx.xxxxxx.net/episodio/168
this is part of my code, only need the number check:
[...]
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/[0-9]',trim($url))){
[...]
Can help me?
Thanks!
If you want to do it with preg_match:
$url = 'http://horadeaventura.enlatino.net/episodio/168';
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/([0-9]+)#',trim($url), $matches)){
$post = $matches[1];
echo $post;
}
So, basically: I added an end delimiter (#), changed "[0-9]" to "([0-9])+", added ", $matches" to capture the matches. Of course it can be done better and using other options than preg_match. But I wanted to make your snippet work - not rewrite it.
If you don't have your heart set on using preg_match(), you could do
$string = "http://xxx.xxxxxx.net/episodio/168";
$array = explode("/", $string);
echo end($array);
which will output
168
this is assuming the number you are looking for will always be the last section of the url string
Or, you can just check for number, on last position:
if(preg_match('#[0-9]+$#',trim($url),$match)){
print_r($match);
}

PHP regexp; extract last part of string

A column in my spreadsheet contains data like this:
5020203010101/FIS/CASH FUND/SBG091241212
I need to extract the last part of string after forwward slash (/) i.e; SBG091241212
I tried the following regular expression but it does not seem to work:
\/.*$
Any Idea?
Try this:
'/(?<=\/)[^\/]*$/'
The reason your current REGEXP is failing is because your .* directive matches slashes too, so it anchors to the first slash and gives you everything after it (FIS/CASH FUND/SBG091241212).
You need to specify a matching group using brackets in order to extract content.
preg_match("/\/([^\/]+)$/", "5020203010101/FIS/CASH FUND/SBG091241212", $matches);
echo $matches[1];
You could do it like this without reg ex:
<?php
echo end(explode('/', '5020203010101/FIS/CASH FUND/SBG091241212'));
?>
this will do a positive lookbehind and match upto a value which does not contain a slash
like this
[^\/]*?(?<=[^\/])$
this will only highlight the match . i.e. the last part of the url
demo here : http://regex101.com/r/pF8pS2
Make use of substr() with strrpos() as a look behind.
echo substr($str,strrpos($str,'/')+1); //"prints" SBG091241212
Demo
You can 'explode' the string:
$temp = explode('/',$input);
if (!empty($temp)){
$myString = $temp[count($temp)-1];
}
You can also use:
$string = '5020203010101/FIS/CASH FUND/SBG091241212';
echo basename($string);
http://www.php.net/manual/en/function.basename.php

preg_match acting very strange

I am using preg_match() to extract pieces of text from a variable, and let's say the variable looks like this:
[htmlcode]This is supposed to be displayed[/htmlcode]
middle text
[htmlcode]This is also supposed to be displayed[/htmlcode]
i want to extract the contents of the [htmlcode]'s and input them into an array. i am doing this by using preg_match().
preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}
The above code outputs
[htmlcode]This is supposed to be displayed[/htmlcode]middle text[htmlcode]This is also supposed to be displayed[/htmlcode]
instead of
[htmlcode]This is supposed to be displayed[/htmlcode]
[htmlcode]This is also supposed to be displayed[/htmlcode]
and if have offically run out of ideas
As explained already; the * pattern is greedy. Another thing is to use preg_match_all() function. It'll return you a multi-dimension array of matched content.
preg_match_all('#\[htmlcode\]([^\"]*?)\[/htmlcode\]#ms', $text, $matches);
foreach( $matches[1] as $value ) {
And you'll get this: http://codepad.viper-7.com/z2GuSd
A * grouper is greedy, i.e. it will eat everything until last [/htmlcode]. Try replacing * with non-greedy *?.
* is by default greedy, ([^\"]*?) (notice the added ?) should make it lazy.
What do lazy and greedy mean in the context of regular expressions?
Look at this piece of code:
preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}
Now, if your pattern works fine and all is ok, you should know:
return statement will break all loops and will exit the function.
The first element in matches is the whole match, the whole string. In your case $text
So, what you did is returned the first big string and exited the function.
I suggest you can check for desired results:
$matches[1] and $matches[2]

Categories