2

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';
5
  • Have you tried anything?? Share your code. Commented Sep 3, 2018 at 5:21
  • @EmptyBrain nope, im confused on how to do it Commented Sep 3, 2018 at 5:22
  • @EmptyBrain Shortcut https? Commented Sep 3, 2018 at 5:24
  • echo preg_replace ('/https|http/','stackoverflow','http://test1.com/'); Commented Sep 3, 2018 at 5:31
  • @EmptyBrain if i have url like this https://sdasdahttpol.com/ it will replace the http after the https, and how to remove the / in the last string character if only the string last character is / Commented Sep 3, 2018 at 5:40

4 Answers 4

6

You can try like:

$test = "https://stackoverflow.com/";
$test = rtrim(preg_replace ('/https|http/','test',$test,1),'/');
echo $test;
Sign up to request clarification or add additional context in comments.

2 Comments

if i have url like this https://sdasdahttpol.com/ it will replace the http after the https,
@TinyDancer Check updated answer
3

You can just use str_replace to solve this,

 $url = rtrim(str_replace(['http://', 'https://', ], 'stackoverflow://', $url), '/');

Comments

0

Try

$url1 = 'http://test1.com/';   
echo str_replace(['http://', 'https://'],'',$url1);

Comments

-1

Try this

echo reConstructUrl('http://test1.com/','stackoverflow');
function reConstructUrl($url,$replace_string){
  return  rtrim(preg_replace ('/https|http/',$replace_string,$url),'/');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.