Link to home
Start Free TrialLog in
Avatar of jccyber
jccyber

asked on

preg replace

Hello Experts,

I am trying to use preg_replace in this scenario

I am trying to replace this: href="/ with this href="http://domain.com/

How?
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

$string = preg_replace("#(href=\")/#","$1http://domain.com/",$string);
You can simply use the following:
$str = "href=\"/";
$str = preg_replace("/href=\"\//", "http://domain.com/", $str);

Open in new window

Please ignore my above post and use the following code instead:
$str = "gwag href=\"/";
$str = preg_replace("/href=\"\//", "href=\"http://domain.com/", $str);

Open in new window

Looking at the example posted here I would say that you do not need a regular expression at all.  Something like this code snippet would be simpler and faster.  If there is more to this question that we are not seeing, please let us know.


<?php

$str = '<a href="/images/picture.jpg">pic</a>';

$old = 'href="/';
$rep = 'href="http://domain.com/';
$new = str_replace($old, $rep, $str);

Open in new window

> Looking at the example posted here I would say that you do not need a regular expression at all.

Agreed, for the description of the problem given. However, if it is desirable to relax the pattern we're trying to match, then using a regular expression allows us to have an unknown number of space characters between "href" and "=" etc. Eg:
$string = preg_replace("#(href\s*=\s*\")/#","$1http://domain.com/",$string);
ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jccyber
jccyber

ASKER

Thank you, TerryAtOpus That is what I was looking for. I need to learn more about preg replace.
@jccyber, going forward, if you post a couple of examples showing the variations on the input theme and the expected outputs, you may get better answers.  For better or worse, computer programming is a fairly literal craft and problem definitions are more than half the battle.  There is certainly nothing wrong with using REGEX and we might even be able to give you more constructive advice about the design of the application if we had a little more visibility into what you are getting as an input and what you want as an output.

Best to all, ~Ray