Jump to content

[SOLVED] searching for string within url


moola

Recommended Posts

How do you find if a certain url contains a certain string. This is pretty trick because I dont really understand the how to get past all the ? /
for example...

How to i write an if statement for [code]$url = http://www.phpfreaks.com/forums/index.php?action=post;board=1.0 [/code]
for example

[code]if ($url has the string "Action")
{
do this;
}
else{
do this;
}[/code]
Link to comment
https://forums.phpfreaks.com/topic/28565-solved-searching-for-string-within-url/
Share on other sites

like.. if you just wanted to see if in $url it has the words "action" then you could do

[code=php:0]
if ($strpos($url, 'action') != false) {
  // action is in there
} else {
  // it's not
}
[/code]

if you wanted to make sure "action" was set and wasn't just "....php?action=;board=1.0" you could use regex (it's a teensy slower... but really not noticable unless you are looping through hundreds of times to do it) you could do...

[code=php:0]
if (pregmatch("/action=[A-Za-z0-9]{1,};/", $url)) {
  // action is in there
} else {
  // it's not
}
[/code]

this only matches letters/numbers between the action= and the ; though, so if you want more than alphanum you'll have to add that to the regex..
(it matches action=cake123; but not action=(a|<3;)

Hope I understood your question right.


[b]Edit:[/b] forgot the {1,} in my regex
[quote author=thorpe link=topic=116401.msg474234#msg474234 date=1164581151]
[code=php:0]
if (isset($_GET['action'])) {
  // action is set
}
[/code]
[/quote]

That's the way of doing it if you aren't checking the string $url, I just assumed since he defined $url in his example that he was meaning to check a string and not the current url.
two functions which do all the work for you in parsing urls are 'parse_url' and 'parse_str':
[code]<?php
$parsetheurl = parse_url($theurl);
if (isset($parsetheurl['query'])) {
    $urlparms = $parsetheurl['query'];
    parse_str($urlparms, $parmsarray);
    //$parmsarray contains all the url passed variables and their names
}
if (isset($parmsarray)) {
    foreach ($parmsarray as $key => $value) {
        //blabla
    }
}
?>[/code]
--works with any url as a string, does not need to be the current url

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.