Do not show code if URL contains phrasses

Discussion in 'PHP' started by postcd, Nov 12, 2014.

  1. #1
    Hello,

    i have an javascript which i want to show only if URL do NOT contains certain phrasses. Like include javascript in webpage only if URL is free from words: cars, motorcycles

    So far i found this code, but it is only for one word:
    
    $url = 'http://' . $SERVER['SERVERNAME'] . $SERVER['REQUESTURI'];
    
    if (false !== strpos($url,'car')) {
    echo 'Car exists.';
    } else {
    echo 'No cars.';
    }
    
    Code (markup):
     
    postcd, Nov 12, 2014 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    PoPSiCLe, Nov 12, 2014 IP
  3. Anveto

    Anveto Well-Known Member

    Messages:
    697
    Likes Received:
    40
    Best Answers:
    19
    Trophy Points:
    195
    #3
    Assuming your code is correct, you could do this for multiple words

    <?php
    $url = 'http://' . $SERVER['SERVERNAME'] . $SERVER['REQUESTURI'];
    $match = false;
    $wordlist = array('motorcycles','car');
    foreach ($wordlist as $w) {
        if (false !== strpos($url,'$w')) {
            $match = true;
        }
    }
    if ($match) {
        echo 'At least one word matched';
    } else {
        echo 'No match';
    }
    
    PHP:
     
    Anveto, Nov 12, 2014 IP
  4. postcd

    postcd Well-Known Member

    Messages:
    1,043
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    190
    #4
    Thank you, i tried that code, but it appears it do not recognize partial phrasses not words, i mean if url is fast-cars-on-sale , and my word is "car", it will still show "No match"
     
    postcd, Nov 13, 2014 IP
  5. postcd

    postcd Well-Known Member

    Messages:
    1,043
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    190
    #5
    Just found one javascript in the meantime and it works beautifully:

    <div id="conditionalbox">
    Visible only if phrasses do not exist in URL
    </div> 
    
    <script>
    if (/car|motorcycle/.test(window.location.href)) {
    document.getElementById('conditionalbox').style.display = 'none';
    }
    </script>
    HTML:
     
    postcd, Nov 13, 2014 IP
  6. Anveto

    Anveto Well-Known Member

    Messages:
    697
    Likes Received:
    40
    Best Answers:
    19
    Trophy Points:
    195
    #6
    Sorry about that, I had some quotes which I forgot to remove, you will see that this works.

    
    $url = 'http://fast-cars-on-sale';
    $match = false;
    $wordlist = array('motorcycles','car');
    foreach ($wordlist as $w) {
      if (false !== strpos($url,$w)) {
      $match = true;
      }
    }
    if ($match) {
      echo 'At least one word matched';
    } else {
      echo 'No match';
    }
    
    PHP:
     
    Anveto, Nov 14, 2014 IP
    postcd likes this.