Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jun 2008
    Posts
    104
    Thanks
    71
    Thanked 0 Times in 0 Posts

    Question Regular expression to check all possibilities

    I've been trying to figure out an easy way to check a string where spaces are allowed yet using a regular expression that matches any number of combinations with spaces in the string, without having to remove all spaces first.

    For example, I have:

    Code:
    $mystring = preg_replace('/[^a-zA-Z0-9\s]/', '', $mystring);
    
    $mystring = preg_replace('/apple|orange/', '', $mystring);
    The above will remove "apple" or "orange", but it still allows "a pple" or "oran ge".

    Now, I know I can simply remove all spaces before checking the string, but I want to allow spaces and keep the string with all original spaces intact.

    So, is there a way to keep the spaces while finding a match?

    Thanks!

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    Strictly speaking you can use something like this:
    PHP Code:
    $mystring preg_replace('/\s*a\s*p\s*p\s*l\s*e\s*|\s*o\s*r\s*a\s*n\s*g\s*e\s*/'''$mystring); 
    But that is not very elegant. What is the problem you're trying to solve? There might be a better way.
    Last edited by Inigoesdr; 02-15-2010 at 10:36 PM. Reason: Changed to allow matching multiple spaces

  • #3
    Regular Coder
    Join Date
    Jun 2008
    Posts
    104
    Thanks
    71
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Inigoesdr View Post
    Strictly speaking you can use something like this:
    PHP Code:
    $mystring preg_replace('/\s*a\s*p\s*p\s*l\s*e\s*|\s*o\s*r\s*a\s*n\s*g\s*e\s*/'''$mystring); 
    But that is not very elegant. What is the problem you're trying to solve? There might be a better way.
    Thanks, that's similar to the code that I came up with, but as you mentioned it's not very elegant, especially if I have a lot of alternates to match.

    I even tried a way to strip the spaces and then somehow replace the spaces with some sort of character that indicates where a space was, but that takes me back to square one again.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •