How can I remove all special characters from the beginning and end of a string, wait # and ,?

advertisements

I have to remove all special characters except # and , from the start and the end of a string.

I tried something like this:

$q = preg_replace('/[^A-Za-z0-9\-\(\) ]/', '', $q);


This should work for you:

As you already used, I use preg_replace() here to replace every character at the start or at the end of a string which isn't # or ,.

$q = preg_replace('/^[^#,]|[^#,]$/', '', $q);

regex explanation:

^[^#,]|[^#,]$

  • 1st Alternative: ^[^#,]

    • ^ assert position at start of the string
    • [^#,] match a single character not present in the list below
      • #, a single character in the list #, literally
  • 2nd Alternative: [^#,]$
    • [^#,] match a single character not present in the list below

      • #, a single character in the list #, literally
    • $ assert position at end of the string