© 2026 Laravel

Native String Functions – Nhanh hơn, rõ ràng hơn so với regex

3 phút đọc 42 lượt xem

#Nguyên tắc cốt lõi

👉 Không dùng regex khi không cần thiết

👉 Với các thao tác đơn giản (start/end/contains/replace/split):

  • Dùng hàm string built-in → nhanh hơn, dễ đọc hơn

#Bad Example (Anti-pattern)

if (preg_match('/^https/', $url)) {
    // starts with https
}

if (preg_match('/\.pdf$/', $filename)) {
    // ends with .pdf
}

if (preg_match('/admin/', $role)) {
    // contains admin
}

$clean = preg_replace('/\s+/', ' ', $text);
$slug = preg_replace('/[^a-z0-9]/', '-', strtolower($title));

#Vấn đề

  • Regex overkill cho logic đơn giản
  • Khó đọc, khó maintain
  • Dễ sai khi escape ký tự

#Good Example (Best Practice)

#1. Starts / Ends / Contains (PHP 8+)

if (str_starts_with($url, 'https')) {
    // starts with https
}

if (str_ends_with($filename, '.pdf')) {
    // ends with .pdf
}

if (str_contains($role, 'admin')) {
    // contains admin
}

#2. Basic string ops

$trimmed  = trim($input);
$lower    = strtolower($name);
$upper    = strtoupper($code);
$replaced = str_replace('old', 'new', $text);

$parts  = explode(',', $csv);
$joined = implode(', ', $items);

#3. Extract substring

$extension = substr($filename, strrpos($filename, '.') + 1);

#4. Khi NÊN dùng regex

$isEmail = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;

$matches = preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $parts);

👉 Pattern phức tạp → regex là đúng

#Giải thích sâu (Senior mindset)

#1. Performance

  • String functions: viết bằng C → rất nhanh
  • Regex: phải compile pattern → chậm hơn (2–10x với case đơn giản)

👉 Với hot path (loop lớn) → khác biệt rõ

#2. Readability

str_contains($s, 'admin')

vs

preg_match('/admin/', $s)

👉 Built-in dễ hiểu hơn, không cần knowledge regex

#3. Escaping pitfalls

Regex cần escape:

  • . + * ? ( )

👉 Dễ bug khi input dynamic

#4. Type safety

  • Hàm string có signature rõ ràng
  • Ít lỗi runtime hơn regex sai pattern

#5. Boundary của regex

👉 Chỉ dùng khi:

  • Pattern phức tạp
  • Validation nâng cao
  • Parsing text

#Tips & Tricks (Senior level)

#1. Rule nhanh

👉 Simple → string function 👉 Complex → regex

#2. Normalize trước khi xử lý

$value = strtolower(trim($value));

👉 Tránh case-sensitive bug

#3. Slug generation (best practice)

$slug = strtolower(trim($title));
$slug = str_replace(' ', '-', $slug);

👉 Regex chỉ khi cần clean sâu hơn

#4. Laravel helpers

Str::contains($text, 'admin');
Str::startsWith($url, 'https');

👉 Wrapper readable hơn

#5. Tránh premature optimization

👉 Không phải lúc nào cũng cần thay regex

#Interview Questions

1. Tại sao không nên dùng regex cho mọi thứ?

Summary:

  • Overkill

Deep: Regex chậm hơn và khó đọc với case đơn giản

2. Khi nào nên dùng regex?

Summary:

  • Pattern phức tạp

Deep: Validation nâng cao, parsing

3. str_contains khác gì preg_match?

Summary:

  • str_contains đơn giản hơn

Deep: Nhanh hơn, không cần pattern

4. str_starts_with hoạt động như thế nào?

Summary:

  • Check prefix

Deep: So sánh substring đầu chuỗi

5. Regex có luôn chậm hơn không?

Summary:

  • Không

Deep: Với pattern phức tạp → regex là tối ưu

#Kết luận

👉 Native string functions giúp:

  • Code rõ ràng
  • Performance tốt hơn
  • Ít bug hơn

👉 Regex là công cụ mạnh, nhưng chỉ dùng đúng chỗ