Memory Refresh
Php



String parsing








Programming Regex, Antipatterns, Php, Git

parse_str ()

<?php // Parses the string into variables // test.php?a=1&&c[]=3&c[]=4 parse_str($_SERVER['QUERY_STRING']); echo $a; // 1 echo $c[1]; // 4

parse_url()

<?php // Parse a URL and return its components $parts = parse_url("Reference print_r($parts); /* Array ( [scheme] => http [host] => doc.com [path] => /test.php [query] => a=1&b=c ) */

strtok(), strrtok()

Note that only the first call to strtok uses the string argument. <?php // Splits a string (str) into smaller strings (tokens) $str = "java.lang.Object"; echo $tok_1 = strtok("java.lang.Object", "."); // java echo $tok_2 = strtok("."); // lang // Get the last part of a string after a given character echo strrev(strtok(strrev("java.lang.Object"), ".")); // tcejbO.gnal.avaj -> tcejbO -> Object <?php // like strstr() echo strtok("name@doc.com", "@"); // name

strspn()

Match a string against a "whitelist" mask of allowed characters <?php // Returns the length of the initial segment of the string that does contain // any of the characters from the mask echo strspn("133445ab123ef", "12345"); // 6 echo strspn("133ab12345ef", "12345"); // 3 echo strspn("ab12345ef", "12345"); // 0 // Using a start & length to search echo strspn("ab12345ef", "12345", 2); // 5 echo strspn("ab12345ef", "12345", 2, 1); // 1 <?php // You can use this function with strlen to check illegal characters. // This function is significantly faster than the equivalent preg_match() $allowed = "0123456789+. "; $phone = "Phone: +021 072.88.544545"; $phone2 = "+021 072.88.544545 (phone)"; echo strspn($phone, $allowed); // 0 echo strspn($phone2, $allowed); // 19 $allowed = "0123456789+. "; $phone = "+021 / 072.88.544545"; if (strlen($phone) == strspn($phone, $allowed)) { echo "allowed"; // not true becouse of "/" char }







Programming Regex, Antipatterns, Php, Git