Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace http or https prefix in string PHP [duplicate]

Tags:

string

regex

php

i have a php variable which contain url string like this:

$url1 = 'http://test1.com/';
$url2 = 'https://test2.com';
$url3 = 'http://test3.com/';

i want to replace the http or https prefix with specific string and remove the dash at the end only if the string variable contain dash at the end of the string, for example:

$url1 = 'stackoverflow://test1.com';
$url2 = 'stackoverflow://test2.com';
$url3 = 'stackoverflow://test3.com';
like image 613
Tiny Dancer Avatar asked Feb 15 '26 03:02

Tiny Dancer


2 Answers

You can try like:

$test = "https://stackoverflow.com/";
$test = rtrim(preg_replace ('/https|http/','test',$test,1),'/');
echo $test;
like image 150
Empty Brain Avatar answered Feb 17 '26 16:02

Empty Brain


You can just use str_replace to solve this,

 $url = rtrim(str_replace(['http://', 'https://', ], 'stackoverflow://', $url), '/');
like image 31
DarkBee Avatar answered Feb 17 '26 18:02

DarkBee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!