Оставляем только цифры php

Содержание
  1. Удаление регулярными выражениями в PHP
  2. Текст и символы
  3. Удалить все пробелы
  4. Удалить двойные пробелы
  5. Удалить лишние пробелы перед знаками препинания
  6. Оставить в тексте только буквы, цифры и пробел
  7. Удалить цифры
  8. Удалить латинские буквы
  9. Удалить русские буквы
  10. Удалить все буквы и цифры
  11. Удалить все кроме цифр и пробелов
  12. Удалить табуляцию
  13. Удалить переносы строк
  14. Удалить определенное количество символов
  15. Удалить текст до определенного символа
  16. Удалить текст после символа
  17. Удалить скобки с их содержимым
  18. Комментарии
  19. Удалить комментарии из HTML
  20. Удаление многострочных комментариев «/* . */»
  21. Удалить комментарии «//» и «#»
  22. Комментарии SQL « —. »
  23. Нумерация строк
  24. Хештеги
  25. Extract Numbers From a String in PHP
  26. Use preg_match_all() Function to Extract Numbers From a String in PHP
  27. Use filter_var() Function to Extract Numbers From a String in PHP
  28. Use preg_replace() Function to Extract Numbers From a String in PHP
  29. Related Article — PHP String
  30. Numbers only regex (digits only) PHP
  31. Basic numbers only regex
  32. Real number regex
  33. Notes on number only regex validation
  34. Create an internal tool with UI Bakery

Удаление регулярными выражениями в PHP

Примеры регулярных выражений для удаления данных из текста.

Текст и символы

Удалить все пробелы

$text = 'a b c d e'; $text = mb_ereg_replace('[\s]', '', $text); echo $text; // abcde

Удалить двойные пробелы

$text = 'a b c d e'; $text = mb_ereg_replace('[ ]+', ' ', $text); echo $text; // a b c d e

Удалить лишние пробелы перед знаками препинания

$text = 'Многие ! известные ? личности , и по сей день .'; echo preg_replace("/\s+([\.|,|!|\?]+)/", '\\1',$text);
Многие! известные? личности, и по сей день.

Оставить в тексте только буквы, цифры и пробел

$text = 'Многие известные. личности, по: сей день.'; echo mb_eregi_replace("[^a-zа-яё0-9 ]", '', $text);
Многие известные личности по сей день

Удалить цифры

$text = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя abcdefghijklmnopqrstuvwxyz 0123456789'; echo mb_eregi_replace('3', '', $text);
абвгдеёжзийклмнопрстуфхцчшщъыьэюя abcdefghijklmnopqrstuvwxyz

Удалить латинские буквы

$text = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя abcdefghijklmnopqrstuvwxyz 0123456789'; echo mb_eregi_replace('[a-z]', '', $text);
абвгдеёжзийклмнопрстуфхцчшщъыьэюя 0123456789

Удалить русские буквы

$text = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя abcdefghijklmnopqrstuvwxyz 0123456789'; echo mb_eregi_replace('[а-яё]', '', $text);

Удалить все буквы и цифры

$text = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя abcdefghijklmnopqrstuvwxyz 0123456789 . '; echo mb_eregi_replace('[\w]', '', $text);

Удалить все кроме цифр и пробелов

$text = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя abcdefghijklmnopqrstuvwxyz 0123456789 . '; echo mb_eregi_replace('[^0-9 ]', '', $text);

Удалить табуляцию

Удалить переносы строк

echo preg_replace("/[\r\n]/", '', $text);

Удалить определенное количество символов

Примеры удаляют девять символов в начале и конце текста.

// Удаление с начала $text = mb_eregi_replace("^.(.*)$", '\\1', $text); echo $text; // Удаление с конца $text = mb_eregi_replace("(.*)[^.]$", '\\1', $text); echo $text;

Удалить текст до определенного символа

Данные регулярные выражения удаляют все что находится до первого искомого символа, а также пробел который идет за ним.

$text = 'Многие известные. личности, по: сей - день.'; // Удалить до пробела echo preg_replace("/^(.*?)(\s)(.*?)$/", '\\3', $text); // Удалить до "." echo preg_replace("/^(.*?)(\.\s)(.*?)$/", '\\3', $text); // Удалить до "," echo preg_replace("/^(.*?)(,\s)(.*?)$/", '\\3', $text); // Удалить до ":" echo preg_replace("/^(.*?)(:\s)(.*?)$/", '\\3', $text); // Удалить до "-" echo preg_replace("/^(.*?)(-\s)(.*?)$/", '\\3', $text);
известные. личности, по: сей - день. личности, по: сей - день. по: сей - день. сей - день. день.

Удалить текст после символа

$text = 'Многие известные. личности, по: сей - день.'; // Удалить после пробела echo preg_replace("/^(.+?)\s.+$/", '\\1', $text); // Удалить после «.» echo preg_replace("/^(.+?)\..+$/", '\\1', $text); // Удалить после «,» echo preg_replace("/^(.+?),.+$/", '\\1', $text); // Удалить после «:» echo preg_replace("/^(.+?):.+$/", '\\1', $text); // Удалить после «-» echo preg_replace("/^(.+?)-.+$/", '\\1', $text);
Многие Многие известные Многие известные. личности Многие известные. личности, по Многие известные. личности, по: сей

Удалить скобки с их содержимым

$text = '(Casio G-SHOCK) [GW-9200-1ER] '; // Удаление (. ) echo preg_replace("/(.*?)\(.*?\)\s?(.*?)/is", '\\1\\3', $text); // Удаление [. ] echo preg_replace("/(.*?)\[.*?\]\s?(.*?)/is", '\\1\\3', $text); // Удаление echo preg_replace("/(.*?)\<.*?\>\s?(.*?)/is", '\\1\\3', $text); // Удаление [. ] echo preg_replace("/(.*?)<.*?>\s?(.*?)/is", '\\1\\3', $text);

Комментарии

Удалить комментарии из HTML

$text = '

Текст текст

'; echo preg_replace('/\s?\s?/', ' ', $text);

Удаление многострочных комментариев «/* . */»

$text = " /** * Описание функции и тд * @param name * @param defaultValue * @returns */ document.write(' '); "; echo preg_replace("/\/\*(.*?)\*\//sm", '', $text);

Удалить комментарии «//» и «#»

$text = " // По возрастанию: ksort($array); # По убыванию: krsort($array);"; $res = preg_replace("/\/\/.*\n/", '', $text); $res = preg_replace("/#.*\n/", '', $res); echo $res;

Комментарии SQL « —. »

$text = " SELECT * FROM `articles` WHERE `name` LIKE '%KEY%' -- OR `title` LIKE '%KEY%' OR `text` LIKE '%KEY%'"; echo preg_replace("/\s--.*\n/", '', $text);
SELECT * FROM `articles` WHERE `name` LIKE '%KEY%' OR `text` LIKE '%KEY%'

Нумерация строк

$text = ' 1 text text text. 2 text text text. 3 text text text. 1. text text text. 2. text text text. 3. text text text. 1) text text text. 2) text text text. 3) text text text.'; echo preg_replace('/(\d)+(\.|\)|\s)+([\s]?)+(.*)/', '\\4', $text);
text text text. text text text. text text text. text text text. text text text. text text text. text text text. text text text. text text text.

Хештеги

$text = 'broken beat, nu jazz, downtempo #nujazz, #downtempo, #intelligent'; echo preg_replace('/#([\S]+)/', '', $text);
broken beat, nu jazz, downtempo 

Источник

Extract Numbers From a String in PHP

Extract Numbers From a String in PHP

  1. Use preg_match_all() Function to Extract Numbers From a String in PHP
  2. Use filter_var() Function to Extract Numbers From a String in PHP
  3. Use preg_replace() Function to Extract Numbers From a String in PHP

In this article, we will introduce methods to extract numbers from a string in PHP.

  • Using preg_match_all() function
  • Using filter_variable() function
  • Using preg_replace() function

Use preg_match_all() Function to Extract Numbers From a String in PHP

We can use the built-in function preg_match_all() to extract numbers from a string . This function globally searches a specified pattern from a string . The correct syntax to use this function is as follows:

preg_match_all($pattern, $inputString, $matches, $flag, $offset); 

This function returns a Boolean variable. It returns true if the given pattern exists.

The program below shows how we can use the preg_match_all() function to extract numbers from a given string .

php $string = 'Sarah has 4 dolls and 6 bunnies.'; preg_match_all('!\d+!', $string, $matches); print_r($matches); ?> 

We have used !\d+! pattern to extract numbers from the string .

Array (  [0] => Array  (  [0] => 4  [1] => 6  )  ) 

Use filter_var() Function to Extract Numbers From a String in PHP

We can also use the filter_var() function to extract numbers from a string . The correct syntax to use this function is as follows:

filter_var($variableName, $filterName, $options) 

The function filter_var() accepts three parameters. The detail of its parameters is as follows

We have used FILTER_SANITIZE_NUMBER_INT filter. The program that extracts numbers from the string is as follows:

php $string = 'Sarah has 4 dolls and 6 bunnies.'; $int = (int) filter_var($string, FILTER_SANITIZE_NUMBER_INT); echo("The extracted numbers are: $int \n"); ?> 
The extracted numbers are: 46 

Use preg_replace() Function to Extract Numbers From a String in PHP

In PHP, we can also use the preg_replace() function to extract numbers from a string . The correct syntax to use this function is as follows:

preg_replace($regexPattern, $replacementVar, $original, $limit, $count) 

We will use the pattern /[^0-9]/ for finding numbers in the string . The program that extracts numbers from the string is as follows:

php $string = 'Sarah has 4 dolls and 6 bunnies.'; $outputString = preg_replace('/[^0-9]/', '', $string); echo("The extracted numbers are: $outputString \n"); ?> 
The extracted numbers are: 46 

Related Article — PHP String

Copyright © 2023. All right reserved

Источник

Numbers only regex (digits only) PHP

Numbers only (or digits only) regular expressions can be used to validate if a string contains only numbers.

Basic numbers only regex

Below is a simple regular expression that allows validating if a given string contains only numbers:

Enter a text in the input above to see the result

Real number regex

Real number regex can be used to validate or exact real numbers from a string.

Enter a text in the input above to see the result

 

Enter a text in the input above to see the result

Notes on number only regex validation

In PHP you can also validate number by using is_numeric function:

Create an internal tool with UI Bakery

Discover UI Bakery – an intuitive visual internal tools builder.

Источник

Читайте также:  Функция возвращающая строку питон
Оцените статью