Search code examples
phpif-statementwpallimport

Check if a string conains a specific word


I need to check if an URL address contains some text. so I created this code.

function url_mapping_name( $urlname ) {
    if (str_contains($urlname, 'amazon.de')) {
    echo "amazon;
}
if (str_contains($urlname, 'brickset')) {
    echo 'brickset';
} else {
    echo 'no URL';
}

I am trying to say. Look for "amazon.de" in $urlname, if the URL contains amazon.de return amazon, if the URL contains brickset.com return brickset, if nothing found return no URL

But something is wrong and I do know where I did a mistake

Thanks for helping me.


Solution

  • The line

    echo 'amazon';

    is missing a quotation mark. Note the color coding changes. That is usually caused by a missing quotation mark.

    Assuming by "return" you mean having the function assign that value to a variable, all the output strings should be

    return 'string';

    instead of

    echo 'string';

    A potential additional issue is having 2 if statements instead of using else if. If you do intent to echo the strings instead of returning them, it should be like this so when it's equal to 'amazon' it doesn't also echo 'no url'

    function url_mapping_name( $urlname ) {
         if (str_contains($urlname, 'amazon')) {
            echo 'amazon';
         } else if (str_contains($urlname, 'brickset')) {
            echo 'brickset';
         } else {
              echo 'no URL';
    }