本文介绍了用户个人资料页面的自定义 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的 PHP 脚本,它以简单的格式显示来自 MySQL 数据库的用户配置文件信息.目前,要查看个人资料,请输入以下链接:

I have a basic PHP script that displays a user's profile information from a MySQL database in a simple format. Currently, to view a profile you enter the following link:

https://xxx.xxx.com/profile.php?id=XXX

但是,我想要的是类似于 Twitter 的内容,其 URL 看起来更像:

However, what I'd like is something similar to Twitter, where the URL looks more like:

https://xxx.xxx.com/profile/UserName

我已经阅读了用户个人资料的友好网址?,但这建议使用:

I have already read friendly urls for users profile?, but that suggested to use:

https://xxx.xxx.com/profile.php?username=UserName

...这不是我想要的.有什么办法可以做到吗?谢谢.

...which is not what I'd like. Is there any way this can be done? Thanks.

推荐答案

试试下面的代码您的 .htaccess 文件将包含此代码

Try the following codeyour .htaccess file will contain this code

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/$    index.php    [L]

RewriteRule ^profile/([A-Za-z0-9-]+)/?$    profile.php?username=$1    [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

注意:从你提供链接的地方把链接作为http://example.com/profile/username

Note : from where you are giving the link just put the link ashttp://example.com/profile/username

如果您的用户名包含空格、字符串,则 url 将不干净,因此请确保用户名不得包含任何特殊字符或空格

If your username contains spaces,strings then url will not be clean so make sure user name must not contain any special character or spaces

用于删除和获取干净的字符串使用下面的函数

for removing and getting clean string use below function

function to_prety_url($str)
{
    if($str !== mb_convert_encoding( mb_convert_encoding($str, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') )
        $str = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    $str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace('`&([a-z]{1,2})(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);`i', '\1', $str);
    $str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace(array('`[^a-z0-9]`i','`[-]+`'), '-', $str);
    $str = strtolower( trim($str, '-') );
    return $str;
}

这篇关于用户个人资料页面的自定义 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 10:04