Глава 28: регулярные выражения (вычитка)

This commit is contained in:
Igor Simdyanov
2022-05-18 10:03:21 +03:00
parent d06e9ae3d0
commit 79048ec3b6
4 changed files with 46 additions and 0 deletions

6
regexp/ex01.php Normal file
View 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
View 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
View 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
View 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>