1

In PHP I have an array like this:

array
  0 => string 'open' (length=4)
  1 => string 'http://www.google.com' (length=21)
  2 => string 'blank' (length=5)

but it could also be like:

array
  0 => string 'blank' (length=5)
  1 => string 'open' (length=4)
  2 => string 'http://www.google.com' (length=21)

now it is easy to find "blank" with in_array("blank", $array) but how can I see if one string is starting with "http"?

I've tried with

array_search('http', $array); // not working
array_search('http://www.google.com', $array); // is working

now everything after `http? could vary (how to write vary, varie? could be different is what I mean!)

Now do I need a regex or how can I check if http exists in array string?

Thanks for advices

3
  • maybe this stackoverflow.com/questions/2354024/… Commented Jan 29, 2014 at 15:39
  • How about a foreach loop with strpos? Commented Jan 29, 2014 at 15:45
  • And there you go, preg_grep() to the rescue ! Commented Jan 29, 2014 at 15:46

4 Answers 4

2

"Welcome to PHP, there's a function for that."

Try preg_grep

preg_grep("/^http\b/i",$array);

Regex explained:

/^http\b/i
 ^\  / ^ `- Case insensitive match
 | \/  `--- Boundary character
 |  `------ Literal match of http
 `--------- Start of string
Sign up to request clarification or add additional context in comments.

Comments

2

Try using the preg_grep function which returns an array of entries that match the pattern.

$array = array("open", "http://www.google.com", "blank");

$search = preg_grep('/http/', $array);

print_r($search);

Comments

2

Solution without regex:

$input  = array('open', 'http://www.google.com', 'blank');
$output = array_filter($input, function($item){
  return strpos($item, 'http') === 0;
});

Output:

array (size=1)
  1 => string 'http://www.google.com' (length=21)

Comments

0

You can use preg_grep

$match = preg_grep("/http/",$array);
if(!empty($match)) echo "http exist in the array of string.";

or you can use foreach and preg_match

foreach($array as $check) {
    if (preg_match("/http/", $check))
    echo "http exist in the array of string.";
}

1 Comment

preg_match() in a loop is extremely slow, better use strpos() in this case

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.