search
HomeBackend DevelopmentPHP TutorialPHP regular expression pattern matching example tutorial

  1. $sub = "bbs.it-home.org";

  2. $ptn = '/w*.w*.w */';

  3. // Regular expression, metadata, returned data

  4. preg_match($ptn, $sub,$mats);
  5. echo "

    "; 
  6. print_r($mats);
  7. echo "";
  8. ?>
  9. //match ip
  10. $str = "my ip is 192.168.10.1sdjlfajdf192 .178.39.4la";
  11. $ptn = '/d+.d+.d+.d+/';

  12. preg_match_all($ptn, $str,$mats);
  13. echo "

    "; 
  14. print_r($mats);
  15. echo "";
  16. ?>

Copy the code

pattern modifier and place it at the end of the regular expression i,m,s,u,e i: ignore case m: Treat as multiple lines s: treated as one line u: Greedy mode, maximum mode e: used when replacing, can be processed with functions, used to match the first parentheses in regular expressions

  1. $str = "Linux and php are lamp or linux is very much";
  2. $ptn = '/linux/i';
  3. preg_match_all($ptn, $str,$mats) ;
  4. echo "
    "; 
  5. print_r($mats);
  6. echo "";
  7. ?>
Copy code

mExample m is treated as multiple lines

  1. $str = "Linux and php are lamp or nlinux is very much";
  2. $ptn = '/^linux/im';
  3. preg_match_all($ptn, $str,$mats
  4. echo "
    "; 
  5. print_r($mats);
  6. echo "";
$str = "Linux and php are lamp or nlinux is very much"; $ptn = '/.*/s'; preg_match_all($ptn, $str,$mats ); echo "
"; 
print_r($mats);
echo "";
    ?>
  1. Copy code
  2. e usage
$str = "123 php";
$ptn = '/d+s(w+)/e';

$rep = 'strtoupper($1)';

// preg_match_all ($ptn, $str,$mats);
$str2 = preg_replace($ptn, $rep, $str);
echo "
"; 
    print_r($str2);
  1. echo "
> ;";
  • ?>
  • Copy code
  • backward reference
  • $str = "123 php";
    $ptn = '/(d+)(s)(w+)/';

    $rep = '$3$2$1';

    // preg_match_all($ptn, $str,$mats);
    $str2 = preg_replace($ptn, $rep, $str);
    echo "
    "; 
      print_r($str2);
    1. echo " pre>";
    2. ?>
    3. Copy code
    4. Five commonly used functions 1. String matching and replacement preg_match(); preg_match_all(); preg_grep(); do a search 2. String replacement preg_replace(); 3. String segmentation preg_split(); eval allows string expressions to be executed Preg_grep example, search:
    //For example, representative article
    $arr = array(

    "php html",

    " linux redhat rhce",
    "junzaivip test php",
    );
      //Need to search The content of
    1. $ptn = '/junzaivip/';
    2. //Return the searched content
    3. $arr2 = preg_grep($ptn, $arr);
    4. echo "
      "; 
    5. print_r($arr2);
    6. echo "";
    7. ?>
    8. Copy code
    9. 4. Mathematical functions 1.max(); 2.min(); Note: 1. Multiple numbers, 2. Arrays composed of multiple numbers
    echo max(3,45,6,7);
    echo "
    ";

    echo max(array(4,6,8,9));

    ? >
      Copy code
    1. 5.Date function 1.time(); 2.date(); //Convert timestamp to date 3.strtotime();//Convert date to timestamp 4.microtime();

      1. //calc Open the calculator
      2. The origin of time:
      3. echo time();
      4. echo "
        ";
      5. echo date("Y-m-d H:i-s w t", 0);
      6. ?>
      Copy code

      Convert time to timestamp

      1. cho strtotime("2014-12-12");
      2. ?>
      Copy code

      to calculate the specific date of the current time:

      1. echo date("Y-m-d H:i:s",time()+8*3600);
      2. ?>
      Copy code

      Find the current time by modifying the time zone date:

      1. //Set China’s time zone as the default time zone
      2. date_default_timezone_set("PRC");
      3. echo date("Y-m-d H:i:s",time());
      4. ?>
      Copy the code

      Note: If each change is troublesome, just modify the php configuration file php.ini file directly, directly modify the date inside, find the timezone and change it to PRC date parameters: Y 2014 full year y In 2014, there were only the last two m 03 month has leading 0 n March has no leading 0 d 05 date has leading 0 j 5 date without leading 0 H 24 hours h 12 hours i 05 minutes s 05 seconds w 0-6 Sunday to Saturday t How many days are there in January 31 L Is it a leap year? //How to distinguish Pingrun years It is divisible by 4, and if it is divisible by 100, it must be divisible by 400. At this time, it is a leap year.

      1. //Set China’s time zone as the default time zone

      2. date_default_timezone_set("PRC");
      3. $y = "1900/1/1";
      4. $time = strtotime ($y);
      5. echo date("L",$time);

      6. ?>
      Copy code

      microtime() Microseconds

      Calculate the running time of the script:

      1. $stime = microtime(1);//Note that this position must be true, otherwise it cannot participate in the calculation
      2. sleep(1);
      3. $etime = microtime(1);
      4. echo $etime - $stime;
      5. ?>
      Copy code

      Example: Perpetual calendar Perpetual calendar technical points 1. Year, month and day 2.Sunday to Saturday What day of the week is 3.1? 4.How many days are there in this month? 5. Next year and previous year 6.Next month and previous month Perpetual calendar code:

      1. //Modify character encoding

      2. //header("content-type:text/html;charset=utf-8");
      3. date_default_timezone_set("PRC") ;
      4. //Get the current year
      5. $year = $_GET['y']?$_GET['y']:date('Y');
      6. //Get the current month
      7. $month = $_GET['m' ]?$_GET['m']:date('m');
      8. //Get how many days there are in the current month
      9. $days = date('t',strtotime("{$year}-{$month}- 1"));//Double quotes must be used inside
      10. //What day of the week is the current first day?$weeks = date('w',strtotime("{$year}-{$month}-1"));
      11. //All content is centered
      12. echo "
        ";
      13. //Output header
      14. echo "

        {$year}year{$month}month

        ";
      15. //Output date Table
      16. echo "";
      17. //Output the first row
      18. echo "
      19. ";
      20. //The header cell is created by th
      21. echo "
      22. ";
      23. echo "
      24. ";
      25. echo "
      26. ";
      27. echo "
      28. ";
      29. echo "
      30. ";
      31. echo "
      32. ";
      33. echo "
      34. > ;";
      35. echo "
      36. ";
      37. //Start laying out the form
      38. for($i = 1 - $weeks;$i echo "
      39. ";
      40. for ($j=0; $j if ($i > $days || $i echo "
      41. ";
      42. } else{
      43. echo "
      44. ";
      45. }
      46. $i++;
      47. }
      48. echo "
      49. ";
      50. }
      51. ";

      52. //Realize the previous year and the previous month
      53. if($month == 1){
      54. $prevyear = $year - 1;
      55. $prevmonth = 12;
      56. } else {
      57. $prevyear = $year;
      58. $prevmonth = $month -1;
      59. }
      60. if($month == 12){
      61. $nextyear = $year + 1;
      62. $nextmonth = 1;
      63. } else{
      64. $ nextyear = $year;
      65. $nextmonth = $month + 1;
      66. }
      67. //Buttons to output the previous month and the next month

      68. echo "

        Previous month|Next month

        ";
      69. echo "";
      70. ?>
      71. Copy codePHP error deal with 1. Turn off and on error reporting 2. Error reporting level 3. Error reporting place

        1), close and enable error reporting E_ALL E_ERROR //serious error E_WARNING //warning error E_PARSE//Syntax error E_NOTICE //Prompt error

        2), close error display_error = off What level of error is reported:

        error_reporting = E_ALL error_reporting = E_ALL & ~E_NOTICE //Report all errors except prompt errors

        3), where to report errors:

        //Whether to report an error from the browser display_error = off //Whether to output errors to a custom log file log_errors = on error_log = d:phplogsphp.log

      72. three four five six
        {$i}

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

    Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

    How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

    Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

    What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

    Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

    How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

    Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

    What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

    The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

    How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

    Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

    What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

    SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

    How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

    Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment