help me understand PHP's preg_replace - php

I have this link:
http://mysite/myfolder/it/my-keywords.html and want to replace /it/ with /es/ (2 letter country codes)
I could explode() with "/" delimiter but would like to understand if preg_replace would be better.
tried:
preg_replace("/\/([a-z]{2})/\/", $link, $country);
EDIT
answer:
preg_replace("/\/[a-z]{2}\//", "/$country/", $link);

preg_replace is like a swiss army knife. preg rather than ereg means it uses perl compatible regular expressions. It matches first param (regex), replaces with second param (string) in third param (string).
Regular expressions are optimized for efficiency by using search tree cutoff techniques etc... so are generally efficient alternative method.
This should do what you want.
preg_replace("/\/it\//","/es/","http://mysite/myfolder/it/my-keywords.html")

preg_replace is useful if you only know a part of string that you want to match, but others parts are variable. In your case the /it/ folder is already unique enough so that a static replacement would work. Use str_replace instead:
$url = str_replace("/it/", "/es/", $url);

Related

Trim URL by variable

Hi I have a Link like this:
mypage.php?product=3&page=1
I want to delete the &page=1, &page=2, &page=5 and so.
I have tried this, but I think it is not right.
str_replace('/(\\?|&)page=.*?(&|$)/', '', $link);
Thanks for your help.
str_replace() doesn't work with regular expressions, so you'd use preg_replace() instead:
$url = preg_replace('/[?&]page=[^&]+/', '', $url);
Two changes here: first, it's better to use a character class instead of alternation when you target individual symbol only (not having to escape ? within the brackets is a nice bonus), second, [^&]+ ('match any number of non-& characters') construct is more direct and readable than .+?(&|$) one.

preg_split url with a regular expression

I have an string e.g.:
src="http://www.domain.com/sub_folder/xyz_17215_andso_on_01-file_08.html"
and want to split this at every character that is not a letter or number.
With
/[a-z0-9]/
I get an array with all the characters but what's the opposite of it to get all the words and numbers?
You can write:
$result_array = preg_split('/[^a-z0-9]+/', $string_to_split);
Rather than writing new code to solve a problem, use the built-in functionality that PHP provides to you in the parse_url() function: http://php.net/manual/en/function.parse-url.php

php what is the equivalent of preg_match but does not require regex?

In PHP is there an equivalent to preg_match that does not require the use of regex? There is str_replace() for preg_replace. Is there something for preg_match.
*update * I am only looking to replace a known string with another. Using regex just seems like overkill.
I have the string "This is a [test1], and not a [test2]" and I want to match them with "[test1]" and "[test2]".
If you mean find a string within another string without using regex, you can use strpos
if (strpos('hello today', 'hello') !== false) {
// string found
}
Since I am not sure what result you are looking for I can't say if this is exactly what you are looking for.
You can use strpos to see if an occurrence of one string is in another.
To answer your question there is some function of PHP without regex
Do not use preg_match() if you only
want to check if one string is
contained in another string. Use
strpos() or strstr() instead as they
will be faster.
But they can not replace preg_match completely at all
First, str_replace() is not replacement for preg_replace(). Function str_replace() replaces all occurrences of the search string with the replacement string, preg_replace() replaces content selected by regular expressions (that's not same thing).
A lot of things require regex (and that's good) so you can't simply replace it with single PHP function.
Most developers use preg_match because they want to use the matches (the third parameter which will get set by the function).
I can not think of a function that will return or set the same information, as done with matches.
If however, you are using preg_match without regex then you might not care as much about the matches.
If you are using preg_match to see if there is a "match" and just that then I'd suggest using strpos instead, since it is much more efficient at seeing if one string is found in another.

How to write regex to find one directory in a URL?

Here is the subject:
http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov
What I need using regex is only the bit before the last / (including that last / too)
The 937IPiztQG string may change; it will contain a-z A-Z 0-9 - _
Here's what I tried:
$code = strstr($url, '/http:\/\/www\.mysite\.com\/files\/get\/([A-Za-z0-9]+)./');
EDIT: I need to use regex because I don't actually know the URL. I have string like this...
a song
more text
oh and here goes some more blah blah
I need it to read that string and cut off filename part of the URLs.
You really don't need a regexp here. Here is a simple solution:
echo basename(dirname('http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov'));
// echoes "937IPiztQG"
Also, I'd like to quote Jamie Zawinski:
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
This seems far too simple to use regex. Use something similar to strrpos to look for the last occurrence of the '/' character, and then use substr to trim the string.
/http:\/\/www.mysite.com\/files\/get\/([^/]+)\/
How about something like this? Which should capture anything that's not a /, 1 or more times before a /.
The greediness of regexp will assure this works fine ^.*/
The strstr() function does not use a regular expression for any of its arguments it's the wrong function for regex replacement.
Are you thinking of preg_replace()?
But a function like basename() would be more appropriate.
Try this
$ok=preg_match('#mysite\.com/files/get/([^/]*)#i',$url,$m);
if($ok) $code=$m[1];
Then give a good read to these pages
http://www.php.net/preg_match
preg_replace
Note
the use of "#" as a delimiter to avoid getting trapped into escaping too many "/"
the "i" flag making match insensitive
(allowing more liberal spellings of the MySite.com domain name)
the $m array of captured results

Simple RegEx PHP

Since I am completely useless at regex and this has been bugging me for the past half an hour, I think I'll post this up here as it's probably quite simple.
hey.exe
hey2.dll
pomp.jpg
In PHP I need to extract what's between the <a> tags example:
hey.exe
hey2.dll
pomp.jpg
Avoid using '.*' even if you make it ungreedy, until you have some more practice with RegEx. I think a good solution for you would be:
'/<a[^>]+>([^<]+)<\/a>/i'
Note the '/' delimiters - you must use the preg suite of regex functions in PHP. It would look like this:
preg_match_all($pattern, $string, $matches);
// matches get stored in '$matches' variable as an array
// matches in between the <a></a> tags will be in $matches[1]
print_r($matches);
This appears to work:
$pattern = '/<a.*?>(.*?)<\/a>/';
([^<]*)
I found this regular expression tester to be helpful.
Here is a very simple one:
<a.*>(.*)</a>
However, you should be careful if you have several matches in the same line, e.g.
hey.exehey2.dll
In this case, the correct regex would be:
<a.*?>(.*?)</a>
Note the '?' after the '*' quantifier. By default, quantifiers are greedy, which means they eat as much characters as they can (meaning they would return only "hey2.dll" in this example). By appending a quotation mark, you make them ungreedy, which should better fit your needs.

Categories