mirror of
https://github.com/igorsimdyanov/php8.git
synced 2025-08-15 23:31:10 +00:00
Глава 28: регулярные выражения (вычитка)
This commit is contained in:
6
regexp/ex01.php
Normal file
6
regexp/ex01.php
Normal file
@ -0,0 +1,6 @@
|
||||
<?php
|
||||
// Проверить, что в строке есть число (одна цифра или более)
|
||||
preg_match('/\d+/s', 'article_123.html', $matches);
|
||||
|
||||
// Совпадение окажется в $matches[0]
|
||||
echo $matches[0]; // выводит 123
|
10
regexp/ex02.php
Normal file
10
regexp/ex02.php
Normal file
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
// Найти в тексте адрес E-mail. \S означает "не пробел", а [a-z0-9.]+ -
|
||||
// "любое число букв, цифр или точек". Модификатор 'i' после '/'
|
||||
// заставляет PHP не учитывать регистр букв при поиске совпадений.
|
||||
// Модификатор 's', стоящий рядом с 'i', говорит, что мы работаем
|
||||
// в "однострочном режиме" (см. ниже в этой главе).
|
||||
preg_match('/(\S+)@([a-z0-9.]+)/is', 'Привет от somebody@mail.ru!', $m);
|
||||
|
||||
// Имя хоста будет в $m[2], а имя ящика (до @) - в $m[1].
|
||||
echo "В тексте найдено: ящик - $m[1], хост - $m[2]";
|
8
regexp/ex03.php
Normal file
8
regexp/ex03.php
Normal file
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
$text = 'Привет от somebody@mail.ru, а также от other@mail.ru!';
|
||||
$html = preg_replace(
|
||||
'/(\S+)@([a-z0-9.]+)/is', // найти все E-mail
|
||||
'<a href="mailto:$0">$0</a>', // заменить их по шаблону
|
||||
$text // искать в $text
|
||||
);
|
||||
echo $html;
|
22
regexp/hsc.php
Normal file
22
regexp/hsc.php
Normal file
@ -0,0 +1,22 @@
|
||||
<?php
|
||||
if (isset($_POST['text'])) {
|
||||
echo htmlspecialchars($_REQUEST['text']) . '<hr />';
|
||||
exit();
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<title>Прием текста от пользователя</title>
|
||||
<meta charset='utf-8' />
|
||||
</head>
|
||||
<body>
|
||||
<form action="hsc.php" method="POST">
|
||||
<textarea name="text" cols="60" rows="10">
|
||||
<?= htmlspecialchars($_POST['text'] ?? '') ?>
|
||||
</textarea><br />
|
||||
<input type="submit">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
|
Reference in New Issue
Block a user