0

I try to covert normal English text to url path.

For example

  • this is a text! -> this-is-a-text
  • this is a text&image -> this-is-a-text-image
  • are you ok? -> are-you-ok

So I try convert it with this code:

str_replace("-", "+", urlencode(trim($text)));

It doesn't covert + to -

Also it seems that doesn't work good for example for '/' and '&' (for some string dosn't work.)

Is there a better way?

luchaninov
  • 6,792
  • 6
  • 60
  • 75
elize
  • 435
  • 1
  • 8
  • 19

2 Answers2

2

For your examples this should work:

$result = preg_replace('/[^a-z0-9]+/i', '-', $text);

If you want all lower-case then use strtolower($text) instead, then no need for the i modifier.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

This process usually is called 'making slug'. You can find various prepared functions for that. Regarding considering Unicode, the function could be more complex.

However, your question is answered here: PHP function to make slug (URL string)

Community
  • 1
  • 1
Mojtaba
  • 4,852
  • 5
  • 21
  • 38