2

So I have an associated array that returns search engine results, it returns a url,title and snippet for each result, I want to find an replace all instances of "http:// and www." from the beginning of each of the urls. This is what I've tried so far, it spits out the url,title and snippet but it doesn't replace the "http:// and www.",

<?php
foreach ($js->RESULT as $item)
    {   
        $blekkoArray[$i]['url'] = ($item->{'url'});         
        $blekkoArray[$i]['title'] = ($item->{'url_title'});
        $blekkoArray[$i]['snippet'] = ($item->{'snippet'});
        $i++;
    }

    $find = array ('http://','www.');
    $replace = array ('','');

    $new_blekkoArray = str_replace ($find, $replace, $blekkoArray);

    print_r ($new_blekkoArray); 
?>  

I'm a bit of a noob at php can anyone help. Regards from Ireland

1
  • str_replace can take an array, but it does not traverse down into sub-arays, e.g. it works with a SINGLE level of an array at a time. Commented Jul 19, 2013 at 18:04

1 Answer 1

3

Try:

$find = array ('http://','www.');

foreach ($js->RESULT as $item)
{   
        $blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );         
        $blekkoArray[$i]['title'] = ($item->{'url_title'});
        $blekkoArray[$i]['snippet'] = ($item->{'snippet'});

        $i++;
}

print_r ($blekkoArray);   
Sign up to request clarification or add additional context in comments.

7 Comments

Suggest doing the replacement during the initial assignment to $blekkoArray[$i]['url'].
and also declaring $find, $replace outside foreach loop.
@Maximus2012 All fair recommendations.
you can probably do away with $i index variable too since its numeric array, the loop iteration will take care of that part.
$replace doesn't have to be an array... can just be an empty string
|

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.