I am trying to search this coincidence in a string:
1. I need to take only numbers after the chracter '#' as long as this coincidence has not spaces, for example:
String = 'This is a test #VVC345RR, text, and more text 12345';
I want to take only this from my string -> 345.
My example:
$s = '\"access_token=103782364732640461|2. myemail#domain1.com ZmElnDTiZlkgXbT8e3 #DD234 4Jrw__.3600.1281891600-10000186237005';
$matches = array();
$s = preg_match('/#([0-9]+)/', $s, $matches);
print_r($matches);
This only works when I have one # and numbers.
Thanks!
Maybe:
#\D*\K(\d+)
Accomplishes what you want?
This will look for an #, any non-numbers, and then capture the numbers. The \K ignores the early match.
https://regex101.com/r/gNTccx/1/
I'm unclear what you mean by has not spaces, there are no spaces in the example string.
Related
I wan to get he text between the HTML comments start and end Like
<!--Q1-->
\nフレンチブルドックと遊んでるとき\n
<!--Q1END-->\n
<!--Q2-->
\n表参道、新宿、銀座\n
<!--Q2END-->\n
<!--Q3-->
\nヒューマンドラマ全般が好きです。<BR>\n<BR>\n好きなアーティスト サザンオールスターズ\n
<!--Q3END-->
I want to get it as array like this
$data = [
1 => 'フレンチブルドックと遊んでるとき',
2 => '表参道、新宿、銀座',
3 = 'ヒューマンドラマ全般が好きです。<BR>\n<BR>\n好きなアーティスト サザンオールスター ズ'
]
So how can i find the text between html comments ?
Thanks in advance
Here's a regex that would get you what you want for the above string:
/<!--Q(\d)-->\n\\n(.*)\\n\n<!--Q\1END-->/gs
(Note: This removes the literal '\n' before and after each of the strings you want since this is what you have above, but if the strings don't have this, it won't match either.)
To put that into PHP remember you have to double escape the literal backslashes. Unfortunately it's quite ugly to keep track of all the newlines and literal '\n' strings (at least to me).
preg_match_all('/<!--Q(\d)-->\n\\\\n(.*)\\\\n\n<!--Q\1END-->/s', $text, $matches);
print_r($matches[2]);
Or if you want something more readable, you can remove the literal '\n' strings from the input text, match everything between the HTML quotes and then trim it:
// Remove all literal '\n' strings from the text
$text = preg_replace('#\\\\n#', '', $text);
// Match desired strings
preg_match_all('/<!--Q(\d)-->(.*)<!--Q\1END-->/s', $text, $matches);
// Trim all desired strings
$output = array_map('trim', $matches[2]);
To get literally what you want lookarounds are good option:
(?<=<!--([A-Z]\d)-->)[\s\S]*?(?=<!--\1END-->)
Demo
Caveat: Works as long as your comment keys (e.g. Q1) do not exceed A0-Z9. You cannot simply use [A-Z]\d+ instead since PHP's/PCRE regex engine does not like quantifiers/variable length patterns in lookbehinds.
Otherwise, I recommend using a capture group like this:
<!--([A-Z]\d+)-->([\s\S]*?)<!--\1END-->
Use it in your code like this:
$re = '/<!--([A-Z]\d+)-->([\s\S]*?)<!--\1END-->/s';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
To get rid of the newline, just use trim(), there are several ways to apply it, e.g. a foreach, a map, etc.
foreach ($matches as $match){
$result[] = trim($match[2]);
}
var_dump($result);
i need your help about how to parse the string. I have a string with structure below :
MALANG|TVhHMTAwMDBK MALANGBONG,GARUT|QkRPMjA3MTlK MALANGKE BARAT,MASAMBA|VVBHMjMzMDVK MALANGKE,MASAMBA|VVBHMjMzMDRK
I'm now confuse how to parse this string so that i can get a pattern like this :
MALANG|TVhHMTAwMDBK
MALANGBONG,GARUT|QkRPMjA3MTlK
MALANGKE BARAT,MASAMBA|VVBHMjMzMDVK
MALANGKE BARAT,MASAMBA|VVBHMjMzMDVK
The pattern output are City_Name|RandomCode
I have try to use explode by space, but the city name sometimes also contains a space. What function in php i could use to solve this problem?
Try this one out. It fits your example ok
$str = 'MALANG|TVhHMTAwMDBK MALANGBONG,GARUT|QkRPMjA3MTlK MALANGKE BARAT,MASAMBA|VVBHMjMzMDVK MALANGKE,MASAMBA|VVBHMjMzMDRK';
$pattern = '/(?<=^| )[A-Z, ]+?\|[A-Za-z0-9]+(?= |$)/';
if (preg_match_all($pattern, $str, $matches)) {
$parts = $matches[0];
}
You may need to tweak some of the character classes if say your city names contain anything other than capital letters, spaces and commas.
Example here - http://codepad.viper-7.com/6ujl3p
Alternatively, if the RandomCode parts are guaranteed to all be 12 characters long, preg_split may be a better fit, eg
$pattern = '/(?<=\|[A-Za-z0-9]{12}) /';
$parts = preg_split($pattern, $str);
Demo here - http://codepad.viper-7.com/Wd4Wmc
I am trying to filter out all characters before the first / sign. I have strings like
ABC/123/...
and I am trying to filter out ABC, 123 and ... into separate strings. I have alsmost succeeded with the parsing of the first letters before the / sign except that the / sign is part of the match, which I don´t want to.
<?php
$string = "ABC/123/...";
$pattern = '/.*?\//';
preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
The letters before the first/ can differ both in length and characters, so a string could also look like EEEE/1111/aaaa.
If you are trying to split the string using / as the delimiter, you can use explode.
$array = explode("/", $string);
And if you are looking only for the first element, you can use array_shift.
$array = array_shift(explode("/", $string));
I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.
I am parsing a web page and need to grab a numeric value from the string, the string is like this
producturl.php?id=736375493?=tm
I need to be able to obtain this part of the string:
736375493
$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
php.net/preg-match
<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>
$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.
There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.
Code (Demo)
$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
Output:
736375493
For completeness, there 8s another way to scan the formatted string and explicitly return an int-typed value. (Demo)
var_dump(
sscanf($str, '%*[^?]?id=%d')[0]
);
The %*[^?] means: greedily match one or more non-question mark characters, but do not capture the substring. The remainder of the format parameter matches the literal sequence ?id=, then greedily captures one or more numbers. The returned value will be cast as an integer because of the %d placeholder.
I'm trying to use regular expressions (preg_match and preg_replace) to do the following:
Find a string like this:
{%title=append me to the title%}
Then extract out the title part and the append me to the title part. Which I can then use to perform a str_replace(), etc.
Given that I'm terrible at regular expressions, my code is failing...
preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches);
What pattern do I need? :/
I think it's because the \w operator doesn't match spaces. Because everything after the equal sign is required to fit in before your closing %, it all has to match whatever is inside those brackets (or else the entire expression fails to match).
This bit of code worked for me:
$str = '{%title=append me to the title%}';
preg_match('/{%title=([\w ]+)%}/', $str, $matches);
print_r($matches);
//gives:
//Array ([0] => {%title=append me to the title%} [1] => append me to the title )
Note that the use of the + (one or more) means that an empty expression, ie. {%title=%} won't match. Depending on what you expect for white space, you might want to use the \s after the \w character class instead of an actual space character. \s will match tabs, newlines, etc.
You can try:
$str = '{%title=append me to the title%}';
// capture the thing between % and = as title
// and between = and % as the other part.
if(preg_match('#{%(\w+)\s*=\s*(.*?)%}#',$str,$matches)) {
$title = $matches[1]; // extract the title.
$append = $matches[2]; // extract the appending part.
}
// find these.
$find = array("/$append/","/$title/");
// replace the found things with these.
$replace = array('IS GOOD','TITLE');
// use preg_replace for replacement.
$str = preg_replace($find,$replace,$str);
var_dump($str);
Output:
string(17) "{%TITLE=IS GOOD%}"
Note:
In your regex: /\{\%title\=(\w+.)\%\}/
There is no need to escape % as its
not a meta char.
There is no need to escape { and }.
These are meta char but only when
used as a quantifier in the form of
{min,max} or {,max} or {min,}
or {num}. So in your case they are treated literally.
Try this:
preg_match('/(title)\=(.*?)([%}])/s', $string, $matches);
The match[1] has your title and match[2] has the other part.