For example, if I wanted to preg_replace the title of a HTML element:
$str = preg_replace('/title=\"([^\"]+)\"/', 'foo', $str);
Please do not give me other solutions (non regex) for this specific example, this is merely an example. I need a solution that works for any regular expressions.
If you want to match parts with preg_replace, but only partially replace something else, then there are two options.
Either you just reinsert the matched parts (enclose in capture groups, and then use $1 and $3):
$str = preg_replace('/(title=")([^"]+)(")/', '$1foo$3', $str);
Or you use assertions:
$str = preg_replace('/(?<=title=")([^"]+)(?=")/', 'foo', $str);
Related
I have three types of strings that I encounter. My goal is to cycle through all of them and just get name.
page_1.name
page_2.name.text
page_1.name.something
The only way I can figure out doing this is to first remove the page_# with the following:
$remove_page = preg_replace("/(page_\d+\.)(\w+)/", "$2", $string);
Then remove the last bit like so:
$get_name = preg_replace("/(\w+)(\.\w+)/", "$1", $remove_page);
Is there a more efficient way to do this? This works, but I feel like I'm only slightly grasping the power of regex.
You can use this regex:
preg_match('/(?<=page_\d\.)[^.]+/', $input, $matches);
(?<=page_\d\.) is a lookbehind that makes sure our match is preceded by page_ and a digit. [^.]+ will match 1 or more characters that are not DOT.
RegEx Demo
Otherwise split by DOT and take 1st element:
$arr = explode('.', $input);
$name = $arr[1];
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+)
Say I have the following string:
$str = "Hello, my name is Bob and I like 'pizza'. Do you like pizza??"
Currently I am able to split/explode this string on the whitespace using:
$arr = explode(' ', $str);
but I want to use the regex pattern \W like so:
$arr = explode('\W', $str);
This should separate all words that aren't punctuation, allowing the 'pizza' part to be separated as pizza. Except it returns nothing (I get an empty array back).
What can I do?
Use preg_split:
http://www.php.net/manual/en/function.preg-split.php
explode does not do Regexen.
preg_split does.
You should use preg_split instead of explode
i'v got such string <>1 <>2 <>3
i want remove all '<>' and symbols after '<>' i want replace with such expression like www.test.com/1.jpg, www.test.com/2.jpg, www.test.com/3.jpg
is it possible to do with regex? i only know to find '/<>.?/'
preg_replace('/<>(\d+)/g', 'www.test.com/bla/$1.jpg', $input);
(assuming your replaced elements are just numbers. If they are more general, you'll need to replace '\d+' by something else).
str_replace('<>', 'www.test.com/', $input);
// pseudo code
pre_replace_all('~<>([0-9]+)~', 'www.test.com/$1.jpg', $input);
$string = '<>1 <>2 <>3';
$temp = explode(' ',preg_replace('/<>(\d)/','www.test.com/\1.jpg',$string));
$newString = implode(', ',$temp);
echo $newString;
Based on your example, I don’t think you need regex at all.
$str = '<>1 <>2 <>3';
print_r(str_replace('<>', 'www.test.com/', $str));
Regex's allow you to manipulate a string in any fashion you desire, to modify the string in the fashion you desire you would use the following regex:
<>(\d)
and you would use regex back referencing to keep the values you have captured in your grouping brackets, in this case a single digit. The back reference is typically signified by the $ symbol and then the number of the group you are referencing. As follows:
www.test.com/$1
this would be used in a regex replace scenario which would be implemented in different ways depending on the language you are implementing your regex replace method in.
There has always been a confusion with preg_match in php.
I have a string like this:
apsd_01_03s_somedescription
apsd_02_04_somedescription
Can I use preg_match to strip off anything from 3rd underscore including the 3rd underscore.
thanks.
Try this:
preg_replace('/^([^_]*_[^_]*_[^_]*).*/', '$1', $str)
This will take only the first three sequences that are separated by _. So everything from the third _ on will be removed.
if you want to strip the "_somedescription" part: preg_replace('/([^]*)([^]*)([^]*)(.*)/', '$1_$2_$3', $str);
I agree with Gumbo's answer, however, instead of using regular expressions, you can use PHP's array functions:
$s = "apsd_01_03s_somedescription";
$parts = explode("_", $s);
echo implode("_", array_slice($parts, 0, 3));
// apsd_01_03s
This method appears to execute similarly in speed, compared to a regular expression solution.
If the third underscore is the last one, you can do this:
preg_replace('/^(.+)_.+?)$/', $1, $str);