Replacing parameter values in URLs - php

// Below are a number of strings which need ammending
$string = "www.development_test.php?action=show_development_crs&test1&test2";
$string = "www.development_test.php?action=show_rfw&test1";
$string = "www.development_test.php?action=show_development_crs";
I need to write a preg_replace() function which replace the value between "=" + "&" or in the case of the bottom string everything after "=" when & doesnt exist with "newAction"..
Does anyone have any ideas?
This is what I have tried so far, but failed:
public function test1()
{
$action = "newAction";
$string = "www.development_crs.php?action=show_development_crs&test1&test2";
$pattern = '/(action=)(.*)(&)/';
$replacement = "action=$action&";
$string = preg_replace($pattern, $replacement, $string);
echo $string;
}

$action = 'newAction';
$string = 'www.development_crs.php?action=show_development_crs&test1&test2';
$pattern = '/action=[^&]+(.*)/';
$replacement = "action=$action$1";
$string = preg_replace($pattern, $replacement, $string);
echo $string;
Output:
www.development_crs.php?action=newAction&test1&test2

try the pattern below
$pattern='/action=([a-z0-9_\-%]+)&/';

$pattern = '/action=.*?(&|$)/';
$replacement = "action=$action$1";

I can see a few problems with your pattern. Not that I'm a regex expert however,
Try something like this:
/action=[^&]+/
or
/action=[^&]*/
This will match 'action=' and then the rest of the string until it encounters a &. The + means that it must have at least one character between the = and the & to accept the string.
Hope this helps :)

Related

Find and replace keyword in a string with PHP

I have this code to find and replace some string if it's between some {{ and }}.
$string = 'This is my {{important keyword}}.';
$string = preg_replace('/{{(.*?)}}/', '$1', $string);
return $string;
How I can change the $1 part to have something like this:
important keyword
So the href needs to have the match item converted like a slug (words separated with a dash, no accent or special char).
Thanks.
You have to use preg_replace_callback() to allow change on matches in a function.
See also use($url) to allow the function to access to the external variable.
Code:
$url = 'https://example.com';
$string = 'This is my {{important keyword}}.';
$string = preg_replace_callback('/{{(.*?)}}/', function($matches) use ($url) {
$newURL = $url . '/' . str_replace(' ', '-', $matches[1]);
return '' . htmlentities($matches[1]) . '';
}, $string);
echo $string;
Output:
This is my important keyword.

How to remove anything character after the part of link from string?

I have make a try like this:
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-13);
and the output work :
localhost/product/-/123456 cause this just for above link with 13 character after /-/123456
How to remove all? i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-(.*));
not work and error sintax.
and i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-999);
the output is empty..
Assume there are no number after localhost/product/-/123456, then I will just trim it with below
$string = "localhost/product/-/123456-Ebook-Guitar";
echo rtrim($string, "a..zA..Z-"); // localhost/product/-/123456
Another non-regex version, but require 5.3.0+
$str = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo dirname($str) . "/" . strstr(basename($str), "-", true); //localhost/product/-/123456
Heres a more flexibility way but involve in regex
$string = "localhost/product/-/123456-Ebook-Guitar";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
$string = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
This should match capture everything up to the number and remove everything afterward
regex101: localhost/product/-/123456-Ebook-Guitar
regex101: localhost/product/-/123456-Ebook-Guitar-1-pdf/
Not a one-liner, but this will do the trick:
$string = "localhost/product/-/123456-Ebook-Guitar";
// explode by "/"
$array1 = explode('/', $string);
// take the last element
$last = array_pop($array1);
// explode by "-"
$array2 = explode('-', $last);
// and finally, concatenate only what we want
$result = implode('/', $array1) . '/' . $array2[0];
// $result ---> "localhost/product/-/123456"

Regular expression for finding multiple patterns from a given string

I am using regular expression for getting multiple patterns from a given string.
Here, I will explain you clearly.
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
The above is my code.
Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??
Now, I need a regular expression that gives me patterns like
about_us, about-us, aboutus as output if i give about us as input.
Is this possible to do.
Please help me in that.
Thanks in advance!
And finally, my answer is
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
You need to do a loop to handle multiple possible outputs :
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
You can try without regex:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
If you put special characters into an array:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
Also you can use just str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.
e.g.
preg_replace('/\W+/', '-', $string);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
I am not sure that regexes are the good tool for that. However you can simply define this kind of function:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
Matches any character that is not a word character
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
in case its just that... you would get problems if it's a longer string :)

PHP String Replacement Not Working Properly

Here is my PHP code,
$string = 'https://www.mydomain.lk/';
$wordlist = array("http://", "www.", "https://", "/");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
echo $string2 = preg_replace($wordlist, '', $string);
I want to remove last "/" from $string.
so i add the "/" to $wordlist array, but its not working.
can somebody help me to fix this.
Thanks.
It seems that for the most part you wish to extract the hostname:
$host = parse_url($url, PHP_URL_HOST);
Removing the leading www. can then be done separately.
preg_replace('/^www\./', '', $host);
You want to only replace / at the end of the string, so you need a $, like /$, but preg_quote would end up escaping the $.
The best way to remove a trailing / is using rtrim, like Sudhir suggested. Alternatively you could remove the preg_quote loop and just use regular expressions in your $wordlist:
$string = 'https://www.mydomain.lk/';
$wordlist = array("#https?://#", "#www\.#", "#/$#");
echo $string2 = preg_replace($wordlist, '', $string);
you could use rtrim():
$string = 'https://www.mydomain.lk/';
echo rtrim($string, '/'); //gives --> https://www.mydomain.lk
Try this
$url= 'https://www.mydomain.lk/';
echo $newurl = rtrim($url,"/");
Output like this format
https://www.mydomain.lk
Please try this:
$string = 'https://www.mydomain.lk/';
$uri = parse_url($string);
$domain = str_replace("www.", "", strtolower($uri['host']));
echo $domain;

Extracting part of a string?

How can I extract 4 from this string?
$string = "Rank_1:1:4";
I'm trying to get pagerank from Googles server, and the last value (4) is the actual pagerank.
Try
$string = "Rank_1:1:4";
$data = explode(':',$string);
echo end($data);
EDIT
as per #MichaelHampton, if they add more fields later, then use as below
$string = "Rank_1:1:4";
$data = explode(':',$string);
echo $data[2];
PHP has so many string function you can use ...
Variables
$find = ":";
$string = "Rank_1:1:4";
Using substr
echo substr($string, strrpos($string, $find) + 1);
Using strrchr
echo ltrim(strrchr($string, $find),$find);
$pattern = '/:\d+$/';
preg_match($pattern, $string, $matches);
$rank = substr($matches[0],1);

Categories