PHP String Replacement Not Working Properly - php

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;

Related

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"

String Replace after the right most character

Here is my character
/public/proj/index.php/home
/public/proj/index.php/test
/public/proj/home
/public/proj/test
I just need to replace the character after the right most '/' to login. So that it will be
/public/proj/index.php/login
/public/proj/index.php/login
/public/proj/login
/public/proj/login
Try this -
$str = "/public/proj/index.php/home";
$vals = explode('/', $str);
$vals[count($vals)-1] = 'login';
$str = implode('/', $vals);
var_dump($str);
This should work for you:
$str = "/public/proj/home";
echo $str = substr_replace($str, "login", -1*(strlen(basename($str))), strlen(basename($str)));
Output:
/public/proj/login

Get number from an url in PHP

I have the following url : http:example.com/country/France/45.
With the pattern http:example.com/country/name/**NUMBER**(?$_GET possibly).
How can I extract the number with a regex (or something else then regex) ?
With regexp:
$str = 'http:example.com/country/France/45';
preg_match('/http:example\.com\/country\/(?P<name>\w+)\/(?P<id>\d+)/', $str, $matches);
print_r($matches); // return array("name"=>"France", "id" => 45);
$url = 'http:example.com/country/France/45';
$id = end(explode('/',trim($url,'/')));
Simple isn't ?
The usage of trim () is to remove trailing \
echo $last = substr(strrchr($url, "/"), 1 );
strrchr() will give last occurence of the / character and then substr() gives string after it.
use something like this
$url = "http://example.com/country/France/45";
$parts = explode('/', $url);
$number = $parts[count($parts) - 1];
and if you have GET variable at the end, you can explode further like this
$number = explode('?', $number);
$number = $number[0];
hope this helps :)
the get command for php is $_GET so to show to number do
<html>
<body>
<?php
echo $_GET["eg"];
?>
</body>
</html>
with a URL of http:example.com/country/name/?eg=**NUMBER**
Use explode():
$parts = explode('/', $url);
$number = $parts[count($parts)-1];

How could replace from the PHP String

I wan't to replace
[a href='url']link[/a]
to
<a href='url'>link</a>
I am using $line = str_replace("[a href='+(.*)+']", "<a href='+(.*)+' >", $line); is not working.
Why not just use:
$search = array('[', ']');
$replace = array('<', '>');
$line = str_replace($search, $replace, $line);
You have to use a regular expression to do this
$line = preg_replace('~\\[a +href=\'([^\']+)\'\\]([^\\[]+)\\[/a\\]~', '$2', $line);
simply use
$string = str_replace(array('[', ']'), array('<', '>'), $string);
This is a great tutorial http://www.youtube.com/watch?v=x9VLWlQhNtM it shows you how to make a small templating engine and it covers what your asking
Try this :
$str = "[a href='url']link[/a]";
$new_str = preg_replace('/\[a href=\'(.*)\'\](.*)\[\/a\]/','<a href=\'$1\'>$2</a>',$str);
echo $new_str;

Reversion Strings and replace a character - RegEx with Php

I have a doubt again on RegEx in Php.
Assume that I have a line like this
716/52 ; 250/491.1; 356/398; 382/144
I want the output to be
Replace all semi-colon with comma. I think I can do this using
$myline= str_replace(";", ",", $myline);
Interchange the numbers and replace '/' with a comma. That is, 716/52 will become 52,716. This is where I get stuck.
So, the output should be
52,716 , 491.1,250, 398,356, 144,382
I know that using sed, I can achieve it as
1,$s/^classcode:[\t ]\+\([0-9]\+\)\/\([0-9]\+\)/classcode: \2\,\1/
But, how do I do it using preg_match in php?
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', 'reverse', $str);
function reverse($matches)
{
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}
var_dump($res);
And working sample: http://ideone.com/BeS9j
UPD: PHP 5.3 version with anonymous functions
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}, $str);
var_dump($res);
As an alternative to Regexen you could try this:
echo join(', ', array_map(
function ($s) { return join(',', array_reverse(explode('/', trim($s)))); },
explode(';', $string)));
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = preg_replace('(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)', '$2,$1', $str);
$str = str_replace(';', ',', $str);
Uses two capture groups, replacing them in reverse order. See it here.

Categories