mldev
mldev

Reputation: 21

PHP in_array and String contains

I have any array of data "example.com/imports", "example.com/var", "example.com/js" i want to remove all urls which contain this for sitemap.

Some of my url data is like the following

"example.com/imports/product.html",
"example.com/imports/product1.html",
"example.com/var/cache/5t46fdgdyg7644gfgfdgr",
"example.com/js/scripts.js"

I have this code

for ($i = 0; $i <= count($urls); $i++) {

$url = $urls[$i];

if (in_array($url, $remove_urls)) {
// found remove url
}else{
echo $url;
}
}

However this only removes if the url is exact match such as "example.com/imports" is there a way to check against start

Upvotes: 0

Views: 5955

Answers (2)

hsz
hsz

Reputation: 152226

Instead of in_array($url, $remove_urls) try to use strpos:

foreach ($urls as $url) {
  $remove = false;

  // loop $remove_urls and check if $url starts with any of them
  foreach ($remove_urls as $remove_url) {
    if (strpos($url, $remove_url) === 0) {
      $remove = true;
      break;
    }
  }

  if ($remove) {
    // remove url
  } else {
    echo $url;
  }
}

Upvotes: 4

pespantelis
pespantelis

Reputation: 15372

You can use preg_grep function like that:

$urls = ['imports', 'var', 'js'];
$url_pattern = '/example.com\/(' . implode('|', $urls) . ')\/.*/';
$removed = preg_grep($url_pattern, $remove_urls);

here an example.

Upvotes: 0

Related Questions