Home > Blockchain >  Check if a string conains a specific word
Check if a string conains a specific word

Time:11-24

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.

CodePudding user response:

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

CodePudding user response:

Thanks for the help, I used the following improvements and it works now.

  1. I fixed the closing quote
  2. replaced echo with return
  3. used elseif - it returned "amazonno URL" before as @aynber wrote
function url_mapping_name( $urlname ) {
    if (str_contains($urlname, 'amazon.de')) {
    return 'amazon';
}
elseif (str_contains($urlname, 'brickset')) {
    return 'brickset';
} else {
    return 'no URL';
}
}

Thank you very much for helping me.

  • Related