PHP ask for a regular expression: keep letters, numbers, underscores, decimal points, dashes in strings

Source: Internet
Author: User
Tags preg
PHP asks for a regular expression: keep the letters, numbers, underscores, decimal points, and dashes in the string.
How to write the regular, thank you ~ ~

Reply content:

PHP asks for a regular expression: keep the letters, numbers, underscores, decimal points, and dashes in the string.
How to write the regular, thank you ~ ~


  
   

Output:

string(15) "AB12@#$%()_.-cd"string(9) "AB12_.-cd"

A mistake in correcting your problem first, simple regular expressions are not able to preserve or remove anything. The function of a regular expression is to match the content that matches the condition.

If you simply want to extract the characters that meet the requirements, try the following code:


  
   

If you want to ensure that only the above conditions are allowed in a string, you can search the Internet, the demand is still many (user name filter), or use the following match (not tested):

$preg = '/([a-zA-Z0-9.\-_]*?)/';

It's too easy to mention. It's a swarmed problem to think of.

An expression is not difficult to write: [a-zA-Z0-9_\-\.]+ .

But on the mechanism, the regular expression must only find a match at a time. Even in the regular interior can be divided into matching groups, that can only be individually matched to the group extraction, can never be "taken out is a good connection." Can't expect everything to one step.

So you have to find all the matches of the small block expression and then join them.

$patt = '/[a-zA-Z0-9_\\-\\.]+/';preg_match_all($patt, $content, $result);echo implode('', $result);
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.