如果我在<form action='./search' method='get'>
内有<input type='text' name='keyword' value='this is the search term' />
在提交表格后,它会引导我/search?keyword=this%20is%20the%search%20term
我应该使用什么正则表达式来捕获这种形式的URL并将其重写为/search-this_is_the_search_term
答案 0 :(得分:1)
首先urldecode搜索字符串,然后用下划线替换空格。 E.g:
$str = "this%20is%20the%search%20term";
$decoded = urldecode($str);
$final = str_replace(' ', '_', $decoded);
您可以更加可靠地使用preg_replace
对正则表达式执行相同的操作,因为您可能需要删除多个连续的空格:
$str = "this%20is%20the%search%20term";
$decoded = urldecode($str);
$final = preg_replace("/\s+/", "_", $decoded);