PHP regular expression practice: matching ISBN code
The ISBN code is a unique identification code for a book and is used to identify the International Standard Book Number. The ISBN code usually consists of 13 digits, of which the last digit is a check code calculated based on the previous 12 digits. In PHP, we can use regular expressions to match ISBN codes to ensure their correctness.
The format of the ISBN code is as follows:
ISBN13: 978-7-111-40543-9
Among them, the first three digits are the EAN country code, the fourth to the sixth The digits are the publisher code, the seventh to twelfth digits are the book number, and the last digit is the check code. For the calculation method of the check code, please refer to this link: https://zh.wikipedia.org/wiki/International_Standard_Book_Number#EAN/UCC-Geographic Code and Check Code.
We can use regular expressions to match ISBN13 codes, as follows:
$pattern = '/^978-[d]{1,5}-[d]{1,7}-[d]{1,6}-[dX]$/';
Among them, "^" and "$" represent the beginning and end of the string; "[d]" represents any A number, "{1,5}" means that the number is repeated 1 to 5 times; "[dX]" means any number or letter X.
Let’s look at a complete PHP code implementation:
<?php function checkISBN($isbn) { $pattern = '/^978-[d]{1,5}-[d]{1,7}-[d]{1,6}-[dX]$/'; if (preg_match($pattern, $isbn)) { $digits = str_replace('-', '', substr($isbn, 0, -1)); $length = strlen($digits); $sum = 0; for ($i = 0; $i < $length; $i++) { $sum += intval($digits[$i]) * (($i % 2 == 0) ? 1 : 3); } $checkDigit = 10 - ($sum % 10); if ($checkDigit == 10) { $checkDigit = 'X'; } return $checkDigit == substr($isbn, -1); } else { return false; } } $isbn = '978-7-111-40543-9'; if (checkISBN($isbn)) { echo $isbn . ' is a valid ISBN!'; } else { echo $isbn . ' is not a valid ISBN!'; } ?>
In this code, we define a function named checkISBN, which receives an ISBN code as a parameter. Internally, the function first uses a regular expression to perform format verification on the ISBN code, then calculates the check code based on the first 12 digits, and finally compares it with the check code of the original ISBN code to determine whether it is valid.
We can save the above code as a PHP file and then execute it in the command line. The output result is:
978-7-111-40543-9 is a valid ISBN!
If the value of $isbn is changed to an illegal ISBN code, such as '978 -7-111-40543-0', the output result is:
978-7-111-40543-0 is not a valid ISBN!
Summary:
Regular expression is a very powerful and flexible tool with wide applicability. In PHP, we can use regular expressions to perform operations such as string matching and format verification. The verification of ISBN codes is also very convenient. Developers can flexibly use regular expressions according to their actual needs to improve code efficiency and maintainability.
The above is the detailed content of PHP regular expression practice: matching ISBN code. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
