Space in a preg match function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hotmodi
    New Member
    • Apr 2010
    • 9

    #1

    Space in a preg match function

    Hi

    How do i get space inside my preg match function?

    Code:
    if (!preg_match('/^[A-ZÆØÅa-zæøå]+$/', $facebook))

    Google is no help today
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    You just add a space. They have no special meaning inside a regular expression, and they are not parsed away like with the PHP code. If you want the regular expression to match a space, you just enter a space.

    For example:
    [code=php]<?php
    $text = 'My name is Atli';
    $regexp = '/^[a-z ]+$/i';

    if(preg_match($ regexp, $text)) {
    echo "Success!";
    }
    else {
    echo "Failure!";
    }
    ?>[/code]
    This echoes "Success!".

    Also note the "i" following the closing delimiter. This makes the match case-insensitive, removing the need to add both upper and lower case letters in the regular expression syntax. Either will match both.

    Comment

    • hotmodi
      New Member
      • Apr 2010
      • 9

      #3
      Thanks that work great;)

      So if I want the user to be able to write http://www.facebook.dk/joe.m

      Should i then write the code like this.

      Code:
      [A-ZÆØÅa-zæøå0-9_-://]+[.]+[A-ZÆØÅa-zæøå]+[.]+[A-ZÆØÅa-zæøå0-9_-://.]

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        no need to make it overly complicated:
        Code:
        defined with the "i" modifyer
        http://(?:[-\w]+\.){1,4}[a-z]{2,4}/[\w.]+
        
        "http://" - obvious
        "(?:)" - a non-capturing group
        "[-\w]" - a hyphen or word character ([a-zA-Z0-9_])
        "{min,max}" - at least [I]min[/I] times and at most [I]max[/I] times
        PS. afaik, URLs allow only ASCII characters

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          PS. afaik, URLs allow only ASCII characters
          That's not true anymore.

          In 2003 the IDN (Internationali zed Domain Name) specification was released, allowing DNS servers to register names using most Unicode characters.

          For backwards compatibility, they are still registered as ASCII strings, but client software compatible with IDNs should allow you to use non ASCII URLs and do the ASCII conversion in the background.
          For example, the URL http://blaðið.is/ is registered as http://xn--blai-dqab.is/. Clicking the second one should work in all browsers, but the first one should only work in IDN capable browsers.

          P.S.
          I have no idea who's website that is. I just picked a random URL with non ASCII chars in it :P

          Comment

          Working...