0

I have an array $all_urls. If I do print_r($all_urls);, it will return the following data:

Array (
[0] => http://www.domain.com
[1] => https://www.domain.com
[2] => http://www.domain.com/my-account/
[3] => https://www.facebook.com/
[4] => /test
[5] => http://domain.com/wp-content/uploads/logos-5.jpg 
[6] => 'http://domain.com/wp-content/themes/'
[7] => '//mattressandmore.com/wp-content/plugins'
)

I would like to extract and list the items that contain "http://" only.

5
  • try to code something first, a foreach is a start Commented May 2, 2015 at 7:58
  • that begins with 'http://' or has 'http://' in it? ie, should element 6 in your array match? Commented May 2, 2015 at 8:19
  • @pala_ correct, it should be a match Commented May 2, 2015 at 8:20
  • Then are you sure the answer you commented on after changing the regexp actually works? it is looking for http only at the start of a string Commented May 2, 2015 at 8:21
  • @pala_ hmm no it didnt.. i didnt realise until you mentioned it but it isnt including the 6th element Commented May 2, 2015 at 8:22

2 Answers 2

1

Use this code to filter only the values that begin with http and return a new array:

array_filter($arr, function ($var) {
    return stripos($var, 'http', -strlen($var)) !== FALSE;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use array_walk function like this:

array_walk($all_urls, function(function(&$value, $index){
    if (preg_match('/^http/', $value)) {
        echo $index . " " . $value . "\n";
    }
});

Also you can just iterate on array with foreach:

foreach($all_urls as $index => $value) {
    if (preg_match('/^http/', $value)) {
        echo $index . " " . $value . "\n";
    }
}

7 Comments

thanks very much. The second solution works well but it did return some https:// whereas i only want http://.. i just updated the preg_match to '/^http:/' and it works pefectly
and finally, if no matches found, how to echo "now matches found" ?
@user3436467 remove the ^ from ^http to change it to match anywhere in the string
also just noticed the 6th element didnt appear, the one that contains a apostrophe at the begining and end 'http://domain.com/wp-content/themes/'
okay great. removing the ^ worked.. just need to include if no matches found echo "no matches found"
|

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.