PHP变量包含字符串并替换

3

我对PHP非常陌生,但我有这段代码:

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

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

有谁知道我该如何让这个工作。

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

谢谢


看一下 str_replace http://php.net/str_replace - jszobody
1
strpos()str_replace()... PHP 文档 非常有用,详细解释了每个函数的用法,并提供了示例... 学会使用它们... 在向他人提问之前,你应该真正利用一下 PHP 文档,而不是让别人花时间回答你的问题 - Mark Baker
http://php.net/manual/en/ref.strings.php - Marc B
另外,考虑将“/en-us/”替换为“/en/”,以避免出现意外结果,例如example.com/en-us/pen-usability变成example.com/en/penability... - Pevara
2个回答

6
$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
}

我希望你能对你有所帮助。

0

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

<?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!";
}
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接