1

I am trying to remove a specific URL from a text string. I have it working for the most part but I need to include both http or https versions of the link.

$link = '<a href="http://example.com/Tool/document.php?id=208" target="_BLANK">Document Requirementsd</a>';

$result = preg_replace('/<a href=\"http:\/\/' . $_SERVER["SERVER_NAME"] . '\/Tool\/document.php\?id=(.*?)\">(.*?)<\/a>/', "\\2", htmlspecialchars_decode($html));

Whats the best way to make sure that both http and https links are stripped?

2 Answers 2

5

You can use (http|https):\/\/ to match both http or https!

Sign up to request clarification or add additional context in comments.

2 Comments

Or just https?://. Remember to escape the slashes if you're using those as delimiters.
Good catch @thomasrutter. I have edited my answer to include the backslashes.
0

So you need

$link = '&lt;a href=&quot;http://example.com/Tool/document.php?id=208&quot; target=&quot;_BLANK&quot;&gt;Document Requirementsd&lt;/a&gt;';
$link = '&lt;a href=&quot;https://example.com/Tool/document.php?id=208&quot; target=&quot;_BLANK&quot;&gt;Document Requirementsd&lt;/a&gt;';

Right?

You use get the https link by replace assuming http as static

//get primary link always http (we need to create http or https isset func)
$link = '&lt;a href=&quot;http://example.com/Tool/document.php?id=208&quot; target=&quot;_BLANK&quot;&gt;Document Requirementsd&lt;/a&gt;';
//making that as https
$https=str_replace('http','https',$link);
//So now you can do whatever you want.
$result = preg_replace('/<a href=\"http:\/\/' . $_SERVER["SERVER_NAME"] . '\/Tool\/document.php\?id=(.*?)\">(.*?)<\/a>/', "\\2", htmlspecialchars_decode($html));

If you want to check if the link is http or https, I can write some more code to find out.

2 Comments

The str_replace will behave incorrectly if the link happens to include the string "http" in it anywhere other than at the start. It will work if the link is constant, but that could just be sample code.
So i can re code it as Finding whether the string has http or https ( if http we can replace the http parts https and check for https and if its https we can replace it to http. Then Output the two Strings https and http

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.