Sobes.tech
Junior

How have you used regular expressions in your projects?

sobes.tech AI

Answer from AI

Used regular expressions for data validation, substring search and replacement, parsing, and working with URIs.

Examples:

  1. Email validation:

    <?php
    $email = "test@example.com";
    if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
        echo "Email is valid.";
    } else {
        echo "Email is invalid.";
    }
    
  2. Finding URLs in text:

    <?php
    $text = "Visit our website https://example.com or contact us at mailto:info@example.com";
    preg_match_all("/\b(?:https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i", $text, $matches);
    print_r($matches[0]);
    
  3. Replacing characters:

    <?php
    $string = "This_is_a_string_with_underscores.";
    $cleaned_string = preg_replace("/[_]/", " ", $string);
    echo $cleaned_string; // Output: This is a string with underscores.
    
  4. Parsing logs:

    <?php
    $log_line = '192.168.1.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326';
    preg_match('/^(\S+) (\S+) (\S+) \[([^\]]+)\] "([^"]+)" (\d+) (\d+)$/', $log_line, $matches);
    print_r($matches);
    /*
    Array
    (
        [0] => 192.168.1.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326
        [1] => 192.168.1.1  // IP address
        [2] => -            // User
        [3] => -            // Group
        [4] => 10/Oct/2000:13:55:36 -0700 // Date and time
        [5] => GET /apache_pb.gif HTTP/1.0 // Request
        [6] => 200           // Status code
        [7] => 2326          // Size
    )
    */
    
  5. Routing (in frameworks): Although I didn't directly write regexes for routing in ready frameworks (Symfony, Laravel), I understood how they are used to match URIs with controllers and actions.

    // Example (simplified, how it might work internally in a router)
    // Route: /users/{id}
    // Regex: #^/users/(\d+)$#
    // Matching /users/123 -> Extracting 123 as ID
    

Overall, I used preg_match, preg_match_all, preg_replace, and preg_split, choosing the function depending on the task.

How have you used regular expressions in your… - sobes.tech