【问题标题】:php variable contains string and replacephp 变量包含字符串并替换
【发布时间】:2016-06-13 00:25:59
【问题描述】:

对 PHP 很陌生,但我有这段代码

$url =  'http://example.com/en-us/about-us';

    if ($url contains 'en-us') {
        replace 'en';
    }

有谁知道我将如何让它工作。

基本上,如果 URL 包含 en-us,则将 url 替换为 en

谢谢

【问题讨论】:

  • 看看str_replacephp.net/str_replace
  • strpos()str_replace()...PHP Docs 非常有用,其中包含有关如何使用每个功能的详细说明和示例...学习使用它们...您应该在请其他人花时间回答您的问题之前,请真正使用PHP Docs
  • Als,请考虑将“/en-us/”替换为“/en/”,以防止出现不必要的结果,例如 example.com/en-us/pen-usability 变成 example.com/en/penability...

标签: php contains


【解决方案1】:
$url =  'http://example.com/en-us/about-us';

if (strpos($url,'en-us') !== false) { //first we check if the url contains the string 'en-us'
    $url = str_replace('en-us', 'en', $url); //if yes, we simply replace it with en
}

希望对你有所帮助

【讨论】:

    【解决方案2】:

    检查字符串是否包含特定单词的简单逻辑如下:

    <?php
    $word = "words";
    $mystring = "this is collection of words";
     
    // Test if string contains the word 
    if(strpos($mystring, $word) !== false){
        echo "Word Found!";
    } else{
        echo "Word Not Found!";
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-09
      • 2018-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2021-06-08
      • 2014-06-12
      • 1970-01-01
      相关资源
      最近更新 更多