Trim URL by variable - php

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.

Related

Using preg_replace to alter youtube links

I want to change the standard youtube video links (like: https://www.youtube.com/watch?v=zVzhpkFBFP8) stored in my database to embeded urls (like: https://www.youtube.com/embed/zVzhpkFBFP8) using preg_replace. This is my code so far:
<?php
$Link = getuser($my_id, 'YoutubeLink');
$LinkNew = preg_replace("/watch?v=*/","embed*/","$Link");
echo "$LinkNew" ?>
But it isn't working. I'm probably doing something stupid but I'm new to php so any help is appreciated.
No need to use preg_replace for something like that in which there is no pattern. As watch?v= is always the same, instead use str_replace('watch?v=', 'embed/', $Link);
Your regex as is doesn't work because the ? is a special character in regex so you need to escape it. The question mark makes the preceding character optional. To escape just add a backslash before it \?.
The * also is being used somewhat incorrectly. The asterisk is a quantifier so you are saying zero or more equal signs. If you wanted everything after the equals sign you'd do .*. That would get every other character because . is any character and paired with the * is everything. You don't actually want to do that either because you aren't grouping that and the replace would just delete it. If you were to group that you could use that value later in the replace using $1. Here's a write up on that http://www.regular-expressions.info/brackets.html.
<?php
$Link = getuser($my_id, 'YoutubeLink');
$LinkNew = preg_replace("/watch\?v=/","embed/", $Link);
echo "$LinkNew"; ?>
As #V13Axel has pointed out though this can be done just as easily using str_replace.

PHP replace with 2 options

I try to delete /en. It works well:
$url = "myDomain/en/firstFolder/secondFolder/file.php";
echo str_replace("/en","",$url);
My problem comes when it could be: /en or /fr. I mean $url could be:
"myDomain/en/firstFolder/secondFolder/file.php";
"myDomain/fr/firstFolder/secondFolder/file.php";
I cannot know if I have /en or /fr. How to delete in both cases?
I tried and of course, it does not work:
echo str_replace("/en|/fr","",$url);
str_replace() is able to accept an array as the first two arguments, for example (from the Docs):
search The value being searched for, otherwise known as the needle.
An array may be used to designate multiple needles.
You can use:
echo str_replace( array('/en', '/fr'), '', $url );
Fiddle Demo
str_replace is used to replace string, If you want to use pattern then use preg_replace
$url = "myDomain/fr/firstFolder/secondFolder/file.php";
echo preg_replace('/\/en|\/fr/','',$url);
If you can't be bothered with making an array of the replacements, use a regular expression:
echo preg_replace('#/(en|fr|es|ru|mm)#', '', $url);
...and you might want to do the following to make sure you don't accidentally trim too much:
echo preg_replace('#/(en|fr|es|ru|mm|fi)/#', '/', $url);
Say your language was Finnish ('/fi') -- you would also effectively get rid of the beginning of '/firstFolder', unless you matched /fi/ with leading and trailing slashes, and substituted it with a single slash. If you can't be bothered enumerating all the languages, you can also simply...
echo preg_replace('#myDomain/[a-z]{2}/#', 'myDomain/', $url);
...which seems like the safest and most elegant way to get there.

Regular expression match for &DaysAgo=3

The title says it all. Just to add that the number can be multiple digits.
I'm using the following function:
str_replace( "/^\&DaysAgo=d+$/", "", $save_query);
str_replace() cannot handle regular expressions. Use preg_replace() for that
As you didn't showed some input data it is hard to give a full example. I'll do it if you update the question and add an example.
Almost there: /^&DaysAgo=\d+$/.
You do not need to escape the ampersand in regex, but in your case, you forgot to put a slash infront of the letter d.
#hek2mgl's comment also applies.

help me understand PHP's preg_replace

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);

php replace problem

there are some url, like 11162_sport.html, 11451_sport.html, 11245_sport.html or 231sport.html,
I want when the url like XXXXX_sport.html then replace them into 11162_football.html, 11451_football.html, 11245_football.html, and 231sport.html has no change.
how to replace them, $newurl = preg_replace("_sport.html","_football.html",$url)? Thanks.
Simply do $newurl = str_replace("_sport.html", "_football.html", $url);
This is faster than doing a preg_replace() and more accurant.
see the manual on str_replace.
you can use str_replace for such simple replacement.
If it must be regular expressions, do:
preg_replace('/_sport\.html$/', '_football.html', $url);
str_replace() would indeterminately replace all occurences of sport.html whereas a regular expression with an end-of-line marker ($) will only replace the pattern at the end of the URL.
The dot needs to be escaped because it would match any character (except new-lines).

Categories