开发者

is there any better way then this for chracter replacement in string?

I am working on my url to make it pretty. and here is the logic i came up with.

now in the url i want to achieve something like this.

http://domain.com/category/date/post-title

for that i first populated the value from the database, i.e date and the post title like this

for date:

$date = date("d", $row['timestamp']);
$month = date("m", $row['timestamp']);
$year = date("Y", $row['timestamp']);
$date_url = $date.$month.$year;

for title:

$title = $row['title'];
$title_url = str_replace(" ", "-", $title);

now i created a hyperlink to send it to URL like this.

<a href="news.php?id=<?php echo $id; ?>&cat=<?php echo 'news'; ?>&date=<?php echo $date_url; ?>&title=<?php echo $title_url; ?>"><img src="<?php echo 'admin-login/'.$pic_title; ?>"/></a>

my main concern is the title, which i am populating the value from the database, is it ok to use str_replace(开发者_StackOverflow社区) for this? or is there any better way?

do i go wrong anywhere or it is fine to go ahead with this logic?

thank you..


You are not considering punctuations and other special char.

You can do:

$from = array('/\W/','/-+/','/^-/','/-$/');
$to = array('-','-','','');
$title = preg_replace($from,$to,$title);

This will replace any non word char to -, replace multiple consecutive -'s with one - and also delete leading and trailing - if any.


Use:

$date = date("dmy", $row['timestamp'])
For title use preg_replace to remove all illegal characters

$title = strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'), array('', '-', ''), $title));


$title = preg_replace('/\W/', '-', $row['title']);


You need to sanitize all special characters in your title, be sure about all of them are eliminated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜