Nếu trước đây chúng ta sử dụng Regular Expression để kiểm tra định dạng dữ liệu thì rất phức tạp phải không nào? Mình cũng vậy, trước đây mình toàn đi lên mạng kiếm những hàm người ta viết sẵn về sử dụng mà không hề biết ý nghĩa của nó như thế nào 🙂 Nhưng bây giờ thì khác vì trong PHP có một module hỗ trợ việc này khá tốt đó là PHP Filters.

PHP Filter là gì?

PHP Filters là một extension được tích hợp sẵn vào thư viện của PHP, đây là một thư viện dùng để kiểm tra tính hợp lệ của dữ liệu (validate data), lọc và xóa đi những ký tự trùng khớp (Sanitizing data). Nếu dịch theo đúng cái tên của nó là bộ lọc trong PHP, như vậy tác dụng của nó cũng chính là ý nghiax của nó. Thông thường chúng ta hay sử dụng PHP Filters để kiểm tra định dạng dữ liệu vì nó tương đối đơn giản. Và trong series này chúng ta sẽ tìm hiểu tổng cộng các loại filter sau:

  • Validate filters
  • Sanitize filters
  • Flag filters
  • Callback filter

Bộ lọc_var

(PHP 5> = 5.2.0, PHP 7)

filter_var – Lọc một biến với bộ lọc được chỉ định

Mô tả ¶

filter_var ( hỗn hợp $variable [, int $filter= FILTER_DEFAULT [, hỗn hợp $options ]]): hỗn hợp

thông số ¶


Giá trị để lọc. Lưu ý rằng các giá trị vô hướng được chuyển đổi thành chuỗi bên trong trước khi chúng được lọc.


ID của bộ lọc để áp dụng. Các loại lọc thủ công trang liệt kê các bộ lọc có sẵn.

Nếu bỏ qua, FILTER_DEFAULTsẽ được sử dụng, tương đương với FILTER_UNSAFE_RAW. Điều này sẽ dẫn đến việc không có bộ lọc diễn ra theo mặc định.


Mảng liên kết của các tùy chọn hoặc phân tách bitwise của cờ. Nếu bộ lọc chấp nhận các tùy chọn, cờ có thể được cung cấp trong trường “cờ” của mảng. Đối với bộ lọc “gọi lại”, loại có thể gọi được sẽ được thông qua. Cuộc gọi lại phải chấp nhận một đối số, giá trị được lọc và trả về giá trị sau khi lọc / vệ sinh nó.

// for filters that accept options, use this format
$options = array(
'options' => array(
'default' => 3, // value to return if the filter fails
// other options here
'min_range' => 0
$var = filter_var('0755', FILTER_VALIDATE_INT, $options);

// for filters that only accept flags, you can pass them directly

// for filters that only accept flags, you can also pass as an array
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
array('flags' => FILTER_NULL_ON_FAILURE));

// callback validate filter
function foo($value)
// Expected format: Surname, GivenNames
if (strpos($value, ", ") === false) return false;
list($surname, $givennames) = explode(", ", $value, 2);
$empty = (empty($surname) || empty($givennames));
$notstrings = (!is_string($surname) || !is_string($givennames));
if ($empty || $notstrings) {
return false;
} else {
return $value;
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));

Return Values ¶

Trả về dữ liệu đã lọc hoặc FALSEnếu bộ lọc bị lỗi.

Ví dụ ¶

Ví dụ # 1 Một ví dụ về bộ lọc_var ()

var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));

Ví dụ trên sẽ xuất ra:

chuỗi (15) "bob@example.com"
bool (sai)


  1. You made some good points there. I looked on the internet for additional
    information about the issue and found most
    people will go along with your views on this site.

  2. Its such as you read my mind! You appear to know so much approximately
    this, like you wrote the ebook in it or something.
    I believe that you just could do with some p.c.

    to pressure the message house a little bit, but instead of
    that, that is excellent blog. A great read. I will certainly
    be back.

  3. My partner and I absolputely love your blog and find many
    of your post’s to be just what I’m looking for. can you offer guest
    writers to write content in your case? I wouldn’t mnd creating a
    post or elaborating on a few of the subjects you write in relation to
    here. Again, awwsome website!

  4. Hmm is anyone else encountering problems with the pictures on this blog loading?
    I’m trying to figure out if its a problem on my end or if it’s the blog.
    Any feedback would be greatly appreciated.

  5. I would like to thank you for the efforts you have put in writing this blog.

    I’m hoping to see the same high-grade content by you in the future as well.
    In fact, your creative writing abilities has encouraged me to get my
    own, personal website now 😉

  6. Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll
    just sum it up what I submitted and say, I’m thoroughly enjoying
    your blog. I too am an aspiring blog writer but I’m still new
    to the whole thing. Do you have any helpful hints for rookie blog writers?
    I’d definitely appreciate it.

  7. Thank you for some other magnificent article. The place else could anyone get that type of information in such a perfect method
    of writing? I’ve a presentation next week, and I’m at the search for such info.

  8. Link exchange is nothing else except it is just placing the other person’s webpage link on your page at proper place and
    other person will also do same for you.

  9. I was suggested this blog by my cousin. I’m not
    sure whether this post is written by him as nobody else
    know such detailed about my difficulty. You’re
    amazing! Thanks!

  10. I truly love your site.. Very nice colors & theme.
    Did you build this web site yourself? Please reply back as I’m attempting to create my own blog
    and want to learn where you got this from or just what the theme
    is called. Thank you!

  11. Do you mind if I quote a few of your articles as long as I provide credit and sources back to your blog?
    My blog site is in the very same area of interest as
    yours and my visitors would truly benefit from a lot of the information you
    provide here. Please let me know if this ok with you.
    Thanks a lot!

  12. I’ve been surfing on-line more than 3 hours nowadays, but I by no means
    discovered any attention-grabbing article like yours. It is lovely value sufficient for me.
    Personally, if all site owners and bloggers made excellent content as you probably did, the web might be much more useful than ever before.

  13. Attractive component of content. I just stumbled upon your website and
    in accession capital to assert that I get in fact enjoyed account your weblog posts.
    Any way I will be subscribing on your feeds and even I fulfillment
    you access constantly fast.

  14. Sweet blog! I found it while surfing around on Yahoo News. Do you have
    any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!

  15. This awesome blog is definitely interesting as well as diverting. I have picked up a lot of useful advices out of this source. I ad love to visit it again soon. Thanks a lot!

  16. Wonderful blog! I found it while browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Thank you

  17. Very interesting information!Perfect just what I was looking for! аАТ’аЂа‹I have great faith in fools аАа’аАТ‚б‚Т€Т self confidence my friends call it.аАТ’аЂа› by Edgar Allan Poe.

  18. Das Beste an diesen kostenlosen Online-Casinos ist, dass sie eine kostenlose Testphase anbieten. Während dieser Zeit können Sie kostenlos spielen und sehen, ob dies die Art von Site ist, an der Sie teilnehmen möchten. Die meisten kostenlosen Mitgliedschaftsseiten bieten eine Geld-zurück-Garantie. Auf diese Weise können Sie die Site verwenden und sehen, ob sie für Sie geeignet ist.

  19. Еще одно преимущество игры в Lets Play Poker онлайн – это разнообразие игр, из которых вы можете выбирать. Эти сайты предлагают множество различных вариантов игр казино. Вы также можете играть в блэкджек и крэпс. Если вы только начинаете, обычно требуется очень небольшая кривая обучения. Как только вы освоитесь, вы можете играть в любую из этих игр бесплатно, а затем выбрать, в каких из них вы хотите участвовать.

  20. Some of these free to join sites even offer a few free games. In some cases you can play for no cost at all and win some freebies. Some of the sites offer monthly membership fees. This can be good if you are just starting out and don’t want to pay for the month to come.

  21. Gunakan kata kunci dalam artikel Anda. Kata kunci adalah bagian penting dari pemasaran artikel. Artikel Anda harus memiliki konten yang bagus karena itu adalah hal pertama yang akan dilihat pembaca. Sebagai penulis artikel, saya dapat memberitahu Anda bahwa kata-kata yang Anda gunakan akan menentukan apakah artikel Anda akan dibaca atau tidak. Jadi, gunakan kata kunci dengan bijak dan ingat untuk memasukkannya ke dalam artikel Anda.

  22. Наконец, расскажите своей аудитории, кто вы и чем занимаетесь. Сделайте это через свой био-бокс. Включите пару предложений о себе или немного о том, что вы делаете. Это даст читателям быстрое представление о вас и о бизнесе, которым вы управляете. Это также поможет вам создать профессиональный имидж, чтобы, когда потенциальные клиенты столкнулись с вашей статьей, они не почувствовали, что вы какой-то интернет-мошенник. Это один из лучших советов по маркетингу статей, который вы когда-либо могли усвоить.

  23. Dies sind die Dinge, die Sie beachten sollten, wenn Sie einen guten Artikel schreiben. Es gibt viele andere Tipps, die Sie im Internet finden können. Sie müssen nur sicherstellen, dass Ihr Artikel interessant und relevant bleibt. Sobald Sie diese Tipps im Hinterkopf behalten, sind Sie auf dem besten Weg, die besten Artikel-Marketing-Tipps zu genießen, die es gibt.

  24. Конечно, вы также должны убедиться, что отправляете заявку на получение купона в соответствующей категории. Большинство сайтов позволяют использовать для купонов только несколько категорий. Если вам не хватает чего-либо из этого, ваше приложение может быть отправлено в корзину. Помните, что вам не обязательно придерживаться купона, который вы найдете на сайте. Подумайте нестандартно и отправьте заявку на получение купона в других категориях.

  25. magnificent post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I am sure, you have a great readers a base already!

  26. This is very interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your great post. Also, I ave shared your site in my social networks!

  27. I was recommended this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my problem. You are incredible! Thanks!

  28. I required to thank you for this interesting We definitely loved each tiny tad of it. I have you bookmarked your identifiable web place to ensure outdated the newest things a person publish.

  29. Very nice info and right to the point. I am not sure if this is actually the best place to ask but do you people have any thoughts on where to employ some professional writers? Thanks in advance

  30. Thank you, I ave recently been searching for information about this topic for ages and yours is the greatest I ave discovered till now. But, what about the bottom line? Are you sure about the source?

  31. Hábitos de riesgo para DE: Tabaquismo, alcohol, drogas, stress. La PDE5 se encuentra en el músculo liso de los cuerpos cavernosos, en el músculo liso vascular y visceral, en el músculo esquelético, las plaquetas, los riñones, pulmones, cerebelo y páncreas. La impotencia o disfunción eréctil puede ser causada por: Causas psicológicas.

  32. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is excellent, let alone the content!. Thanks For Your article about sex.

  33. I was recommended this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are wonderful! Thanks!

  34. Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!. Thanks For Your article about &.

  35. Nice post. Thanks for sharing this exciting post with us. I enjoy at the time of reading this post. You have done a awesome job by sharing this post with us. Keep it up.

  36. My brother recommended I might like this blog. He was entirely right. This post actually made my day. You can not imagine just how much time I had spent for this information! Thanks!

  37. Merci pour les bons post. Je étais enquêter ce sujet pour un jour . Les objets et caractéristiques que vous montrez , je n’étais pas attentif . Je serai suivant votre blog maintenant et J’espère vous pouvez extra Idées et idées.

  38. It is the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions. Maybe you could write next articles referring to this article. I want to read even more things about it!

  39. Wow, awesome weblog structure! How long have you ever been running a blog for? you make blogging look easy. The entire look of your web site is great, let alone the content!

  40. Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is magnificent, let alone the content!

  41. As a teacher, I like to focus a lot on [This student]. I always enjoy when he participates during my lessons. When he is focused, he works very diligently. I see him use new words he has learned in class frequently. He is able to copy my pronunciation of new words very well. If he practices his reading more, he will read even more confidently. It’s always great to read his writing in his English diary. As long as he is focused in class, [This student] will continue to do well.

  42. Nice post. I learn something more challenging on completely different blogs everyday. It can always be stimulating to read content material from other writers and practice a little one thing from their store. I’d prefer to use some with the content material on my weblog whether or not you don’t mind. Natually I’ll provide you with a hyperlink in your web blog. Thanks for sharing.

  43. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  44. Hello would you mind letting me know which web host you’re using? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a reasonable price? Thanks, I appreciate it!

  45. indeed, research is having to pay off. sure, study is having to pay off. My personal web surfing seem total.. thank you. I appreciate you showing your point of view..

  46. I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You ave made my day! Thanks again

  47. This blog is definitely rather handy since I’m at the moment creating an internet floral website – although I am only starting out therefore it’s really fairly small, nothing like this site. Can link to a few of the posts here as they are quite. Thanks much. Zoey Olsen

  48. Very nice info and straight to the point. I am not sure if this is really the best place to ask but do you guys have any ideea where to hire some professional writers? Thanks

  49. My brother suggested I might like this blog. He was totally right. This post truly made my day. You cann at imagine simply how much time I had spent for this info! Thanks!

  50. In other words, how do i search for blogs that fit what I want to read about? Does anyone know how to BROWSE through blogs by subject or whatever on blogger?.

  51. you’re in point of fact a just right webmaster. The site loading speed is incredible. It seems that you are doing any unique trick. Also, The contents are masterpiece. you’ve performed a wonderful task on this topic!

  52. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  53. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!


Please enter your comment!
Please enter your name here