3

My latest issue involves trying to find "http://" in a variable. This variable contains the contents of a comments section on a clients website. I have seen all kinds of answers but none of them seem to work. I looked at a few other posts on here and I have yet to get the best answer. Here is what I have so far:

if(strpos($comments, 'http://') == true) {
  // Does stuff here
}

I noticed other people use preg_match and some said to do it in an array. I am getting confused, too many options. Just kidding. I would like some clarification though and any advice would be greatly appreciated.

1
  • In that post they did === instead of ==, I will give that a try. Commented Jun 6, 2012 at 19:21

3 Answers 3

11

You'll need to say:

if(strpos($comments, 'http://') !== false) {

...since it can return 0 (which is falsey) if http:// is at the beginning of the string.

NOTE: This will only find the first occurrence of http:// in the string.

Take a close look at the reference: http://php.net/manual/en/function.strpos.php

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

8 Comments

So >= will search the whole string?
strpos() will search the whole string until the first occurrence of the needle is found or until end-of-string is reached.
Thank you very much, I'll give this a try and see how it turns out. The main thing I am trying to do is block links in the comments.
Actually, str_ireplace() may be more what you want, then. php.net/manual/en/function.str-ireplace.php
Would this work even if I don't want to replace the http://? In most cases I get spam comments like "byfrgpvsipvtfok, habyqiupyh , [url=---------------.com]ceasdfasdfasdfg[/url], --------------.com habyqiupyh", I want to keep the form from submitting when it comes across the http://.
|
4

You need to change code like that:

if(strpos($comments, 'http://') === false) {

//no link }

because strpos return integer which is position your string.

Example: full string: "http://stackoverflow.com hello" you finding: "http"

Naturally it return 0.

But full string: "ahttp://stackoverflow.com" you finding: "http"

it return 1.

So you must use === operator to check is really 'boolean false'.

If you try to check with == operator, you maybe get fail because it get 0 as false.

more detail: http://php.net/strpos

Comments

0

I found this was a better match: (recommended by phpstorm ide)

if(str_contains($e, '1062 Duplicate entry')) {
            
}

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.