Preg Match issues - php

I've been stuck with a fairly simple preg_match for a while and was wondering if someone could help me out.
Here is what im trying to do.
$string = 'Sub Total£24.00Shipping£5.95Grand Total£29.95Email:';
$m = preg_match('/Shipping(.*?)\Grand/s', $string, $match);
the array $match is returning empty and I really cant understand why.

The \G token is the "last match" position anchor (like in PERL).
You need to esacape it:
\\G
More info:
The anchor \G matches at the position where the previous match ended. During the first match attempt, \G matches at the start of the string in the way \A does.
Source: http://regular-expressions.mobi/continue.html

It looks like you shouldn't have the \ before Grand. The sequence \G must mean something.

Related

PHP match for strings between two (starting, ending) delimters

String;
RandomValue1:|RandomSentence1.|RandomValue2:|RandomSentence2.|
I'm trying to match RandomSentence1. and RandomSentence2.. I figured the "." in the sentence could be used to help the matching since every sentence ends with a period. So if I don't have the period in my match. I'm OK with that. I've never been very good at RegEx but I'm always willing to try and learn. Through the results on here I haven't been able to come up with anything that works. I'd be coding this in PHP. I believe either preg_match() or preg_split() would be the usage here.
I initially tried; .*:\|.*\.\|
But that just matches the entire string since it ends with .|.
Then I tried this; .*:\|\s*(.*?)\s*\|
But that only matched the RandomSentence2.
These are adaptions of what I've found online.
This should work for a regex to capture all. Look for NOT . or | followed by . and |:
preg_match_all('/([^.|]+\.)\|/', $string, $matches);
print_r($matches[1]);
An alternate if you want to do something with the other entries would be to split and then find what you want. Split on | then grep for array values ending in .:
$matches = preg_grep('/\.$/', explode('|', $string));
Since you already know there is a dot at the end, you can just match all
with something simple (?<=\|)[^|.]+(?=\.\|)
https://regex101.com/r/ZsHcWq/1
(?<= \| )
[^|.]+
(?= \.\| )

find specific words in a string then push to array

Consider :
$array=array();
$string = "an url link: url('example.com/abc'),another url link :url('example1.com/foo=bar')";
if (preg_match("regex expression of url('')")
array_push("the whole url string start from 'url(' then end with ')'");
Suppose I have the code above , how to write the above statement in the correct way ?
http://www.phpliveregex.com/p/fE0
preg_match_all("/url\(\'(.*?)\'\)/", $inputSTR, $output);
preg_match_all will match all parts of the string that meet the criteria.
\( and\' means escape regex and make it literal. In short, make sure the ( is a ( and not a part of the regex pattern.
(.*?) match anything and be lazy. This means to only match till first time the regex is no longer matched.
\'\) the end of the search pattern

preg_replace with Regex - find number-sequence in URL

I'm a regex-noobie, so sorry for this "simple" question:
I've got an URL like following:
http://stellenanzeige.monster.de/COST-ENGINEER-AUTOMOTIVE-m-w-Job-Mainz-Rheinland-Pfalz-Deutschland-146370543.aspx
what I'm going to archieve is getting the number-sequence (aka Job-ID) right before the ".aspx" with preg_replace.
I've already figured out that the regex for finding it could be
(?!.*-).*(?=\.)
Now preg_replace needs the opposite of that regular expression. How can I archieve that? Also worth mentioning:
The URL can have multiple numbers in it. I only need the sequence right before ".aspx". Also, there could be some php attributes behind the ".aspx" like "&mobile=true"
Thank you for your answers!
You can use:
$re = '/[^-.]+(?=\.aspx)/i';
preg_match($re, $input, $matches);
//=> 146370543
This will match text not a hyphen and not a dot and that is followed by .aspx using a lookahead (?=\.aspx).
RegEx Demo
You can just use preg_match (you don't need preg_replace, as you don't want to change the original string) and capture the number before the .aspx, which is always at the end, so the simplest way, I could think of is:
<?php
$string = "http://stellenanzeige.monster.de/COST-ENGINEER-AUTOMOTIVE-m-w-Job-Mainz-Rheinland-Pfalz-Deutschland-146370543.aspx";
$regex = '/([0-9]+)\.aspx$/';
preg_match($regex, $string, $results);
print $results[1];
?>
A short explanation:
$result contains an array of results; as the whole string, that is searched for is the complete regex, the first element contains this match, so it would be 146370543.aspx in this example. The second element contains the group captured by using the parentheeses around [0-9]+.
You can get the opposite by using this regex:
(\D*)\d+(.*)
Working demo
MATCH 1
1. [0-100] `http://stellenanzeige.monster.de/COST-ENGINEER-AUTOMOTIVE-m-w-Job-Mainz-Rheinland-Pfalz-Deutschland-`
2. [109-114] `.aspx`
Even if you just want the number for that url you can use this regex:
(\d+)

How to preg_match '{95}1340{113}1488{116}1545{99}1364'

i want to preg_match following as it is
$this_string = '{95}1340{113}1488{116}1545{99}1364';
My best try was
preg_match('/^[\{\d+\}\d+]+$/', $this_string);
That matches
{95}1340{113}1488
but also
{95}1340{113}
which is wrong.
I know why it is matching last example. One match {95}1340 was true, so '+' 'll be always true. But i don't know how to tell, if it match, so it has always be a complete match in '[…]'
i do expect only matches likes these
{…}…
{…}…{…}…
{…}…{…}…{…}…
one of the tries:
^(\{\d+\}\d+)+$
does also match
{99}1364
at the very last end of this string as a second match, so i get back an Array with two Elements:
Array[0] = {95}1340{113}1488{116}1545{99}1364 and
Array[1] = {99}1364
Problem is unnecessary use of character class in your regex i.e. [ and ].
You can use:
'/^(\{\d+\}\d+)+$/'
The translation of your regex to a clearer thing would be: /^[\{\}0-9+]+$/, this would be explained as everything that is inside this chracters {}0123456789+, exactly those ones.
What you want is grouping, for grouping, parentheses are needed and not character classes () instead [], so what you want to do is replace [] for ().
Short answer: '/^(\{\d+\}\d+)+$/'
What you are trying to do is a little unclear. Since your last edit, I assume that you want to check the global format of the string and to extract all items (i.e. {121}1231) one by one. To do that you can use this code:
$str = '{95}1340{113}1488{116}1545{99}1364';
$pattern = '~\G(?:{\d+}\d+|\z)~';
if (preg_match_all($pattern, $str, $matches) && empty(array_pop($matches[0])))
print_r($matches[0]);
\G is an anchor for the start of the string or the end of the previous match
\z is an anchor for the end of the string
The alternation with \z is only needed to check that the last match is at the end of the string. If the last match is empty, you are sure that the format is correct until the end.

php regex matching first and last

i'm new to regular expressions and would like to match the first and last occurrences of a term in php. for instance in this line:
"charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie"
i would like to just access the first and last "charlie", but not the two in the middle. how would i just match on the first and last occurrence of a term?
thanks
If you know what substring you're looking for (ie. it's not a regex pattern), and you're just looking for the positions of your substrings, you could just simply use these:
strpos — Find position of first occurrence of a string
strrpos — Find position of last occurrence of a char in a string
Try this regular expression:
^(\w+),.*\1
The greedy * quantifier will take care that the string between the first word (\w+) and another occurrence of that word (\1, match of the first grouping) is as large as possible.
You need to add ^ and $ symbols to your regular expression.
^ - matches start of the string
$ - matches end of the string
In your case it will be ^charlie to match first sample and charlie$ to match last sample. Or if you want to match both then it will be ^charlie|charlie$.
See also Start of String and End of String Anchors for more details about these symbols.
Try exploding the string.
$names = "charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie";
$names_array = explode(",", $names);
After doing this, you've got an array with the names. You want the last, so it will be at position 0.
$first = $names_array[0];
It gets a little trickier with the last. You have to know how many names you have [count()] and then, since the array starts counting from 0, you'll have to substract one.
$last = $names_array[count($names_array)-1];
I know it may not be the best answer possible, nor the most effective, but I think it's how you really start getting programming, by solving smaller problems.
Good luck.

Categories