Help with regexes code for preg_replace

I have read some tutorials on the formatting / syntax of regexes, but it is way too far over my comprehension abilities as a new coder.

I want to create a code that will do these these things:

  1. Remove most special characters (all special characters except _ - &)
  2. Convert Ampersand (&) to “and”
  3. Convert spaces or underscore to dashes.
  4. Do nothing with dashes.

Could someone please help me out with this? I’m guessing I will have to do this in multiple steps, such as:

  1. $string = preg_replace(only the special characters I noted above in #1, ‘’, $string);
  2. $string = str_replace(‘&’, ‘and’, $string);
  3. $string = preg_replace(and spaces or underscores, ‘-’, $string);

EDIT:
Although, now that I look at that, if I changed the order, and did #2, and then #3, then in #1 I could just replace all special characters except dashes, with no character.

“all special characters”

Define.

Do you mean… everything that isnt a letter or a number? (And do you only mean the latin letters/numbers?)

Do 2, do 3, and then do 1 as “Anything that isnt a word character or a dash.”

Give it a try; regex101.com might be helpful to you there…

preg_replace can take an array of patterns and replacements, so you can condense it somewhat.

Then show us how you got on, and we can refine :slight_smile:

Here is an example
https://www.php.net/manual/en/function.preg-replace.php#example-4838

You can use a ^negative character group. For example [^a-z:] would match all characters that are not lowercase letters or colons.

(Tho really, who creates their array from index 2 to index 0…)

1 Like

I just used an Array literal in my test.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.