简体   繁体   English

有没有更好的办法在PHP中剥离/形成此字符串?

[英]Is there a better way to strip/form this string in PHP?

I am currently using what appears to be a horribly complex and unnecessary solution to form a required string. 我目前正在使用看起来非常复杂且不必要的解决方案来形成所需的字符串。

The string could have any punctuation and will include slashes. 该字符串可以有任何标点符号,并包含斜杠。

As an example, this string: 例如,此字符串:

Test Ripple, it\'s a comic book one!

Using my current method: 使用我目前的方法:

str_replace(" ", "-", trim(preg_replace('/[^a-z0-9]+/i', ' ', str_replace("'", "", stripslashes($string)))))

Returns the correct result: 返回正确的结果:

Test-Ripple-its-a-comic-book-one

Here is a breakdown of what my current (poor) solution is doing in order to achieve the desired output:- 以下是我目前(较差)的解决方案正在实现所需输出的详细信息:

  1. Strip all slashes from the string 去除字符串中的所有斜杠
  2. remove any apostrophes with str_replace 用str_replace删除所有撇号
  3. remove any remaining punctuation using preg_replace and replace it with whitespace 使用preg_replace删除所有剩余的标点符号,并将其替换为空格
  4. Trim off any extra whitespace from the beginning/end of string which may have been caused by punctuation. 修剪掉可能由标点符号引起的字符串开头/结尾的所有多余空格。
  5. Replace all whitespace with '-' 将所有空格替换为“-”

But there must be a better and more efficient way. 但是必须有一个更好,更有效的方法。 Can anyone help? 有人可以帮忙吗?

Personally it looks fine to me however I would make one small change. 就我个人而言,这看起来不错,但是我会做一个小的更改。

Change 更改

preg_replace("/[^a-z0-9]+/i"

to the following 到以下

preg_replace("/[^a-zA-Z0-9\s]/"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM