2

I have a simple php and jquery chatroom for my users. I am currently replacing the www. and http:// strings with a linked url version of them to make links clickable. This works awesome, but does not catch https:// links. What do I change to make it do http or https? Here is the current code

$find = 'http://';
$check_for_links = strpos($message, $find);
if($check_for_links === false) {
    $message = preg_replace('/((www)[^ ]+)/', '<a href="http://$1">$1</a> ', $message);
} else {
    $message = preg_replace('/((http:\/\/)[^ ]+)/', '<a href="$1">$1</a> ', $message);
}
3
  • Add the s and make it optional. https?: Commented Mar 9, 2017 at 22:42
  • doesn't recognize the s: regex101.com/r/3RYM1H/2 Commented Mar 9, 2017 at 22:43
  • You need a space otherwise the [^ ] keeps consuming in your test. regex101.com/r/3RYM1H/3 or change the [^ ]+ to \S+. Commented Mar 9, 2017 at 22:46

2 Answers 2

2

Use preg_match function instead of strpos to "catch" both http and https scheme:

if (!preg_match("/https?:/", $message)) {
    $message = preg_replace('/((www)[^ ]+)/', '<a href="http://$1">$1</a> ', $message);
} else {
    $message = preg_replace('/((https?:\/\/)[^ ]+)/', '<a href="$1">$1</a> ', $message);
}
Sign up to request clarification or add additional context in comments.

Comments

1

It worked perfectly in PHP

str_replace(["https://", "http://"], ["", ""], "https://stackoverflow.com/");

Comments

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.