skip to Main Content

I’m receiving a string from user for fields lable that can contain special characters and HTML tag as well.

Examples:
  1. How will you be attending the event?
  2. select Education Level <i>some instruction</i>

I want to trim the string before any special character. How can it do?

Note: there is no specified special character list. excluded characters are _,-, +. Users can provide any of the characters they desire. But we can target commonly used special characters $%&*()}{@#~?><,|= those are used in questionnaire/instruction statements.

Desire Output:
  1. How will you be attending the event
  2. select Education Level

3

Answers


  1. Chosen as BEST ANSWER

    I used regex expression. It worked for me.

    if (preg_match('/['^£$%&*()}{@#~?><,|=+¬-]/', $str)) {
       $str = preg_split('/['^£$%&*()}{@#~?><,|=+¬-]/', $str)[0];
    }
    

    Explanation:
    1. In the if condition, I'm checking the special characters existence within the string.
    2. If found, then splitting the string into an array.
    3. array index 0 contains a string before the special character and its an expected result.

    If anyone has any suggestions plz let me know.


  2. Try:

    h*[$%&*()}{@#~?><,|=].*$
    

    and replace with an empty string.

    See:
    https://regex101.com/r/tWqcfr/latest
    https://3v4l.org/lPNUs


    Explaination:

    Match what you do not need and throw it away

    • h* Optionally match any leading horizontal whitespace before …
    • [$%&*()}{@#~?><,|=] …encoundtering a special symbol…
    • .*$ …and match the rest of the string.
    Login or Signup to reply.
  3. Try this simple example (demo – https://3v4l.org/tYvI1):

    preg_match('/^[ws+-]+/', 'select Education Level <i>some instruction</i>', $matches);
    echo $matches[0];
    
    1. [ws+-] – means any letter, digit, space, _, -, +
    2. ^ – start of the row
        • one or more
          So you will get all words since start row to any special symbol to $matches array. Obviously the array will have onle one element in your case because of the "start row" condition.

    Best regards,
    Anton

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search