Rewrite url not working with hyphen "-" using .htaccess with php
Get the solution ↓↓↓I'm trying to make my url user-friendly by using .htaccess rewrite.
from url - http://localhost/Web/new_products.php?cat_id=1&cat_title=new-rocket
to url - http://localhost/Web/new-rocket-1.php
in my new_products.php
$get_cat = "select * from new_products_cat";
$run_cat = mysqli_query($con, $get_cat);
while($row_cat = mysqli_fetch_array($run_cat)){
$cat_id = $row_cat['cat_id'];
$cat_title = $row_cat['cat_title'];
$hyphen_cat_title = str_replace(' ', '-', $cat_title);
echo "
<a href='new_products.php?cat_id=$cat_id&cat_title=$hyphen_cat_title'>
......
......
......
in my .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{THE_REQUEST} /Web/new_products.php\?cat_id=([^&\s]+)&cat_title=([^&\s]+) [NC]
RewriteRule ^ /Web/%2-%1\.php? [NC,R,L,NE]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]+)-([^.]+)\.php$ /Web/new_products.php?cat_id=$2&cat_title=$1 [QSA,L,NC]
</IfModule>
Question 1
My code working only if i use "underscore". $hyphen_cat_title = str_replace(' ', '_', $cat_title);
But not working if i use "hyphen", its keep redirecting to http://localhost/Web/new_products.php
Question 2
Can i replace "space" to "hyphen" using rewrite in .htaccess? without using php str_replace
Answer
Solution:
For my Question 1
The problem was [^-] “every character but a hyphen”. Thanks to @CBroe
Below code fixed my problem.
RewriteRule ^([^.]+)-([^.]+)\.php$ /Web/new_products.php?cat_id=$2&cat_title=$1 [QSA,L,NC]
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.