【问题标题】:PHP in_array and String containsPHP in_array 和 String 包含
【发布时间】:2015-01-15 10:07:12
【问题描述】:

我有任何数据数组"example.com/imports", "example.com/var", "example.com/js" 我想删除包含此站点地图的所有 url。

我的一些url数据如下

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

我有这个代码

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

$url = $urls[$i];

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

但是,只有在 url 完全匹配时才会删除,例如 "example.com/imports" 是否有办法检查 start

【问题讨论】:

  • 你想删除什么?

标签: php arrays string contains


【解决方案1】:

尝试使用strpos,而不是in_array($url, $remove_urls)

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;
  }
}

【讨论】:

  • 谢谢!效果很好,只是在 strpos 中将 $remove_urls 更改为 $remove_url
  • 也许我在这里是一个效率书呆子,但我更喜欢if( substr($url,0,strlen($remove_url)) === $remove_url),因为strpos 会在失败之前检查字符串的所有位置,而这只检查第一个 - 我们的那个对XD感兴趣
【解决方案2】:

你可以像这样使用 preg_grep 函数:

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

here 一个例子。

【讨论】:

    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2010-12-04
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多