Jump to content

Is there a PHP character placeholder?


Fluoresce

Recommended Posts

$requestURI = $_SERVER['REQUEST_URI'];

if($requestURI == '/articles/1') {
     // do something
}

I want the above code to be executed if the page URI is /articles/1, /articles/2, /articles/3, etc.

 

Does PHP have a character placeholder to put in place of "1" so that the code will execute no matter what number appears after /articles/?

 

I've checked online but couldn't find one. :confused:

 

 

Link to comment
https://forums.phpfreaks.com/topic/283196-is-there-a-php-character-placeholder/
Share on other sites

Use URL rewriting so you don't have to do this work yourself.

 

For example, with Apache, mod_rewrite, and a .htaccess you do

RewriteEngine on
RewriteRule ^articles/(\d+)$ articles.php?id=$1 [L,QSA]
Then make articles.php use $_GET["id"] to decide what article to show.

Use URL rewriting so you don't have to do this work yourself.

 

For example, with Apache, mod_rewrite, and a .htaccess you do

RewriteEngine on
RewriteRule ^articles/(\d+)$ articles.php?id=$1 [L,QSA]
Then make articles.php use $_GET["id"] to decide what article to show.

 

 

Thanks. I've already done that. This is something different.

 

How can I get the code to execute no matter what appears after /articles/?

One way would be preg_match

if(peg_match('#/articles/\d+/?#', $requestURI) {
     // do something
}

The above should match /articles/1 or /articles/102356

 

But if your using mod_rewrite then just check if the page id exists (refer to requinix example)

if(isset($_GET['id']))
{
   // do something
}

There is no wildcard character. You have to change your condition to either substring out a prefix and match that to '/articles/' or use preg_match and a regex to test the value.

 

eg:

if (substr($requestURI, 0, 10) == '/articles/')
or

if (preg_match('#^/articles/\d+#', $requestURI))

Lots of ways depending on what you want to achieve overall.  Here are two:

$requestURI = $_SERVER['REQUEST_URI'];
$something  = basename($requestURI);

if($something == '/articles') {
     // do something
}
if(preg_match('#/articles/\d+#', $requestURI)) {
     // do something
}

EDIT: I'm late today.

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.