开发者

PHP - url question

开发者 https://www.devze.com 2023-02-01 05:36 出处:网络
How can I turn example 1 into example 2 using PHP Example 1 http://www.example.com/categories/fruit/apple/green

How can I turn example 1 into example 2 using PHP

Example 1

http://www.example.com/categories/fruit/apple/green

Example 2

http://www.example.com/categories/index.php?cat=fruit&sub1=apple&sub2=gre开发者_运维百科en


As has been suggested, this is something to be done through HTACCESS and mod_rewrite rules. The best trick for things like this would be to have a go, share what you have managed to come up with (and the results or bugs) and people will then help you find a complete solution.

That being said, I would suggest something like the following, in a file called ".htaccess" in your webroot.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f # Means if the requested address is not a file
RewriteCond %{REQUEST_URI} !-d # Means if the requested address is not a dir
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?cat=$1&sub1=$2&sub2=$3

I have not tested the above code, but it would be where I would start, and maybe mix with some independent research as required...

Some links:

  • http://www.htmlist.com/how-to/a-simplemod_rewrite-tutorial/
  • http://www.workingwith.me.uk/articles/scripting/mod_rewrite
  • http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html
  • http://www.easymodrewrite.com/guide-syntax


That's just simple string manipulation - but note that changing the request URI within* your script won't automatically populate the relevant $_GET variables.

To change the string:

  <?php
  $input_url='http://www.example.com/categories/fruit/apple/green';
  $parts=parse_url($input_url);
  $embeds=explode('/',$parts['path']);
  $new_path=array_shift(embeds) . '/index.php'; // store 'categories' for later
  $count=1;
  $join=strlen($parts['qry']) ? '&' : '?';
  foreach ($embeds as $val) {
      $parts['query'].=$join . 'ub' . $count . '=' . urlencode($val);
      $join='&';
  }
  $out_url=$parts['scheme'] . '://' 
     . ($parts['username'] . $parts['password']) ? 
             $parts['username'] . ':' $parts['password'] . '@' : ''
     . $parts['host'] . '/' . $new_path
     . $parts['query']
     . '#' . $parts['fragment'];
  print $out_url;
0

精彩评论

暂无评论...
验证码 换一张
取 消