- ereg — Совпадение с регулярным выражением
- Описание
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Примечания
- Смотрите также
- Почему этот стандарт Reg Ex не работает в функции PHP ereg
- Глюк регулярных выражений в PHP при работе с UTF-8
- rgbeast
- 1234ru
- rgbeast
- 1234ru
- 1234ru
- Serg_pnz
- Serg_pnz
- 1234ru
- 1234ru
- Serg_pnz
- 1234ru
- Serg_pnz
- Serg_pnz
- 1234ru
- Serg_pnz
- dskarataev
- 1234ru
- Ereg php не работает
- Описание
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Смотрите также
- User Contributed Notes 24 notes
ereg — Совпадение с регулярным выражением
ereg — Совпадение с регулярным выражением
Описание
Ищет в строке string совпадения с регулярным выражением, заданным в pattern регистрозависимым образом.
С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.
Список параметров
Регулярное выражение, чувствительное к регистру.
Если совпадения найдены для подстрок в скобках из pattern , и функция вызывается с третьим аргументом regs , совпадения будут сохранены в элементах массива regs .
$regs[1] будет содержать подстроку, которая начинается с первой левой круглой скобки; $regs[2] будет содержать подстроку, начинающуюся со второй, и т.д. $regs[0] будет содержать полную копию совпавшей строки.
Возвращаемые значения
Возвращает длину совпавшей строки, если совпадение c pattern найдено в string , или FALSE , если совпадений не было или возникла ошибка.
Если необязательный параметр regs не передан, или длина совпавшей строки равна 0, функция возвращает 1.
Список изменений
Версия | Описание |
---|---|
4.1.0 | Вплоть до (и включая) PHP 4.1.0 $regs будет заполняться точно десятью элементами, хотя реально может совпасть больше или меньше десяти подстрок в скобках. Это не влияет на способность ereg() совпадать с большим количеством подстрок. Если совпадения не найдены, $regs не будет изменен функцией ereg() . |
Примеры
Пример #1 Пример использования ereg()
Следующий фрагмент кода принимает дату в формате ISO (YYYY-MM-DD) и печатает её в формате DD.MM.YYYY:
Примечания
С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED . Смотрите список отличий для помощи при конвертировании в PCRE.
Функция ereg() является устаревшей начиная с PHP 5.3.0. Предлагается использовать вместо неё функцию preg_match() .
Смотрите также
- eregi() — Совпадение с регулярным выражением без учёта регистра
- ereg_replace() — Осуществляет замену по регулярному выражению
- eregi_replace() — Осуществляет замену по регулярному выражению без учета регистра
- preg_match() — Выполняет проверку на соответствие регулярному выражению
- strpos() — Возвращает позицию первого вхождения подстроки
- strstr() — Находит первое вхождение подстроки
- quotemeta() — Экранирует специальные символы
Источник
Почему этот стандарт Reg Ex не работает в функции PHP ereg
Я немного новичок в Reg Ex и не совсем понимаю разницу между различными ароматами. Тем не менее, у меня есть базовый Reg Ex, который работает, когда я пытаюсь его использовать через систему UNIX (vi и grep), но не тогда, когда я пытаюсь использовать его в PHP ereg. Я подозреваю, что есть что-то другое в функции PHP ereg, которая делает это неработоспособным:
Я хотел бы, чтобы это выводило Feugiat hendrerit sit iriuredolor aliquam. без тегов em. Однако он просто возвращает пустую строку.
Функции PHP ereg используют очень ограниченный аромат regex, называемый POSIX ERE. Мой сравнение вкуса указывает на то, что этого вкуса не хватает по сравнению с современными вкусами.
В вашем случае граница слова \b не поддерживается. Строгая реализация POSIX будет указывать \b как ошибку.
Вместо этого вы должны использовать функции preg:
По сравнению с другими полученными вами ответами: Не оставляйте обратную косую черту в \b и используйте $1 для замены. preg_replace использует другой текстовый синтаксис замены, чем ereg_replace.
Вам может потребоваться скрыть обратную косую черту:
Это потому, что \b в строке PHP означает нечто отличное от \b в регулярном выражении. Использование \\ в строке PHP проходит через один обратный слэш на ereg_replace() . Это по той же причине вам нужно использовать двойную обратную косую черту в заменяющей строке «\\1» .
В зависимости от вашего приложения вы также можете рассмотреть возможность того, что ваш вход $string не содержит тегов . В этом случае приведенные выше утверждения приведут к пустой строке, которая, вероятно, не та, которую вы намереваетесь.
Вероятно, рекомендуется избегать ereg для будущей совместимости. Похоже, что он был обесценен в php6 в соответствии с this.
Расширение ereg, поддерживающее регулярные выражения Portable Operating System Interface (POSIX), удаляется из основной поддержки PHP.
ereg_replace не поддерживает утверждение границы слова (\ b) или не-жадный модификатор (*?). PEZ прав, вероятно, вы должны использовать preg.
Дополнительная обратная косая черта не является строго необходимой, потому что PHP не заменяет \b, но это хорошая идея всегда избегать обратных косых черт в строковом литерале.
Если вы используете регулярное выражение для удаления html-тегов, возможно, более удобна функция php strip_tags().
Источник
Глюк регулярных выражений в PHP при работе с UTF-8
Нашел такую вещь: если указывать модификатор ‘u’ (PCRE_UTF8), который предписывает интерпретировать шаблон как строку в utf-8 (см. также http://ru2.php.net/manual/ru/reference.pcre.pattern.modifiers.php), для русских букв работает регистронезависимое сопоставление, но в то же время русские буквы не считаются буквами!
Особенно странное заключается в том, что без модификатора буква распознаётся (хотя регистронезависимое сопоставление, конечно же, не работает, что, впрочем, не странно):
Неожиданным оказалось, что, если сохранить скрипт, например, в кодировке cp-1251, то сопоставление букв разного регистра может проходить успешно:
Проверялось всё это на PHP 5.2.4 под Windows.
Немало удивил также результат проверки на PHP 5.1.6 под Linux: отсутсвие совпадения для всех шести описанных случаев, т.е. модификатор PCRE_UTF8 не работает вообще.
Что бы с этим сделать, как думаете?
rgbeast
А работает ли mb_ereg_replace? Функция конечно требует расширение mb.
Ответить
1234ruecho mb_regex_encoding ( ‘utf-8’ ) ; // выведет 1 — установление кодировки прошло удачно Такая же ситуация с mb_ereg(). Проверялось под Linux (PHP 5.1.6). Кстати, я что-то не пойму, зачем было делать две разных функции: mb_ereg() и mb_ereg_match(). rgbeastСинтаксис у функцмм другой, модификаторов нет: Опции — третий аргумент | 07.12.2008, 01:20 Ответить |
16.03.2009, 15:57 Ответить |
20.03.2009, 19:58 Ответить |
21.03.2009, 15:01 Ответить |
Serg_pnzЕще одна заморочка для utf-8 Пользователь вводит данные на русском языке и проверка уже не работает. Пришлось извратиться так 1234ruЕсли $regLoginTmp содержит нелатинские буквы, и данные в UTF-8, то нужно использовать не strlen, а mb_strlen (в стандартном пакете PHP её нет, нужно устанавливать доп. модуль) Как бы то ни было, с рег. выражением Вы перемудрили: #(.)<1,1># — то же, что просто #.# 🙂 Serg_pnzdskarataevТак что же все-таки является самым правильным решением? 1.каждый раз при использовании регулярных выражений делать конвертацию через iconv() хотелось бы конечно третье 🙂 | 07.10.2010, 17:27 Ответить |
Версия | Описание |
---|---|
4.1.0 | Вплоть до (и включая) PHP 4.1.0 $regs будет заполняться точно десятью элементами, хотя реально может совпасть больше или меньше десяти подстрок в скобках. Это не влияет на способность ereg() совпадать с большим количеством подстрок. Если совпадения не найдены, $regs не будет изменён функцией ereg() . |
Примеры
Пример #1 Пример использования ereg()
Следующий фрагмент кода принимает дату в формате ISO (YYYY-MM-DD) и печатает её в формате DD.MM.YYYY:
Смотрите также
- eregi() — Совпадение с регулярным выражением без учёта регистра
- ereg_replace() — Осуществляет замену по регулярному выражению
- eregi_replace() — Осуществляет замену по регулярному выражению без учёта регистра
- preg_match() — Выполняет проверку на соответствие регулярному выражению
- strpos() — Возвращает позицию первого вхождения подстроки
- strstr() — Находит первое вхождение подстроки
- quotemeta() — Экранирует специальные символы
User Contributed Notes 24 notes
I think this is not clear:
«the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched. «
Beacause By «substring,» it means the string contained within the parenthesis.
But in that statement it isn’t so clearly
Amir Hossein Estakhrian
I wanted a more strict check for UK postcodes, and decided to do it by stripping all whitespace then using ereg:
= str_replace ( » » , «» , $in_post_code );
if (! ereg ( ‘^[a-zA-Z]<1,2>8<1,2>[a-zA-Z]<0,1>9<1>[a-zA-Z]<2>$’ , $pcode ))
<
return false ;
>
?>
Probably could be improved, as I’ve just started, but it matches everything listed on the post office spec.
UK postcode validation.
We’ve used the expression put forward by tomas and jaik,
but we found that it fails on Coventry (CV) postcodes.
Here is an alternative that works for these postcodes and
also adds support for the Overseas Territories like Tristan da Cunha.
function IsPostcode ( $postcode ) <
$postcode = strtoupper ( $postcode );
if( ereg ( «((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)»
. «|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)»
. «|[A-PR-UWYZ](6<1,2>|([A-HK-Y]8″
. «|[A-HK-Y]7(3|[ABEHMNPRV-Y]))»
. «|5[A-HJKS-UW]) 4[ABD-HJLNP-UW-Z]<2>)» , $postcode )) <
return $postcode ;
> else <
return FALSE ;
>
>
Here a little clear and easy script
that I wrote to validate an E-Mail Input.
I tried to understand ereg,
but the describtion on php.net did not help me,
so I made some research and finally (think)
that Im sure how to use ereg.
The following function works for me well and allows
an E-Mail to contain the following characters:
«A-Z, a-z, 0-9, . , — , _ «
function validateMail ( $mail ) <
if( $mail !== «» ) <
if(! ereg ( «^[A-Za-z0-9\.|-|_]*
[@]<1>[A-Za-z0-9\.|-|_]*[.]<1>[a-z]<2,5>$» , $mail )) <
echo «wrong Input for E-Mail» ;
$mail = «» ;
return $mail ;
>
else <
return $mail ;
>
>
>
?>
to make it clear:
^ means begin here (startpoint of ereg)
$ means end here (endpoint of ereg)
* stand for endless characters (I want A-Z, a-z, 0-9 and the other characters to apear from 0 to endless
optional you can write <1,5>for
min 1 times a character or max 5 times a
characters instead of *
<1,2>means min 1 time a character and max 2 times a character (optional you can write * intead of <1,2>
<1>stand for max 1 time a character
\ means from here special characters (like .-_$ and so on)
| means OR
«If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.»
This is very confusing. Reads as ereg() will always return 1 if you don’t pass the OPTIONAL parameter. If that was the case, the parameter wouldn’t be optional as the function would be completly useless without it. Of course the function ereg() still returns 0 if no match was found.
Hi,
for those looking for email adress PHP validation,
isemail is a javascrit function that checks the following conditions for the email string:
• only one @ sign permitted
• domain extension separator (.) must come after the @ symbol
• must be at least 2 characters (letters) after the domain extension separator (.)
• rejects all illegal characters including spaces.
• Allows only numbers, letters, the underscore (_) and the dash (-) character as valid input
(excluding the mandatory «@» and «.» symbols).
• Minimum of 6 characters
The following pattern satisfy all-in-one for the ereg function:
$pattern = «^([A-Za-z0-9\.|-|_]<1,60>)([@])»;
$pattern .=»([A-Za-z0-9\.|-|_]<1,60>)(\.)([A-Za-z]<2,3>)$»;
Here is a series of useful regular expressions.
function isValid ( $type , $var ) <
$valid = false ;
switch ( $type ) <
case «IP» :
if ( ereg ( ‘^(6<1,3>\.)<3>8<1,3>$’ , $var )) <
$valid = true ;
>
break;
case “URL” :
if ( ereg ( «^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu)$» , $var )) <
$valid = true ;
>
break;
case “SSN” :
if ( ereg ( «^2<3>[- ]2<2>[- ]9<4>|8<9>$» , $var )) <
$valid = true ;
>
break;
case “CC” :
if ( ereg ( «^(8<4>[- ])<3>4<4>|1<16>$» , $var )) <
$valid = true ;
>
break;
case “ISBN” :
if ( ereg ( «^7<9>[3|X|x]$» , $var )) <
$valid = true ;
>
break;
case “Date” :
if ( ereg ( «^(82|3)\/(26|3[01]|7)\/7<4>|(51|6)-(24|3[01]|8)-2<4>$» , $var )) <
$valid = true ;
>
break;
case “Zip” :
if ( ereg ( «^8<5>(-4<4>)?$» , $var )) <
$valid = true ;
>
break;
case «Phone» :
if ( ereg ( «^((\(5<3>\) ?)|(3<3>-))?7<3>-4<4>$» , $var )) <
$valid = true ;
>
break;
case “HexColor” :
if ( ereg ( ‘^#?([a-f]|[A-F]|4)<3>(([a-f]|[A-F]|4)<3>)?$’ , $var )) <
$valid = true ;
>
break;
case “User” :
if ( ereg ( «^[a-zA-Z0-9_]<3,16>$» , $var )) <
$valid = true ;
>
break;
>
return $valid ;
>
#Example:
$phone = «789-1234» ;
if ( isValid ( «Phone» , $phone )) <
echo «Valid Phone Number» ;
> else <
echo «Invalid Phone Number» ;
>
?>
It’s important to note for certain regular expression that your $regs[] array will only contain as many values as you have sets of parenthesis in your regexp. (plus 1, of course) For example, the regexp below was designed to locate tags enclosed in <> characters inside a string:
( «^([^ ]+>[^ , $str , $tags ) ?>
This will *not* create an arbitrarily long array in $tags for the number of tags that it finds. Given the string «This a of in it», you’ll see:
0 : This a of in it
1 : This
2 : in it
Since the same parenthesized section of the regexp is matching all tags found, it overwrites the same section of the array. If you try increasing the number of parenthesis, it just creates duplicates of the same result.
I had problem using is_numeric() to verify if user inputs is a number (including optional floating sign and decimals). Instead I found this expression from http://www.regular-expressions.info/floatingpoint.html and modified it for a bit.
/*
3.55 true
-3.55 true
+3.55 true
2456.90 true
34skd false
23. false
2dt6 false
*/
Note: mine doesn’t have the exponent part; for matching number with exponents, visit the site above 🙂
While this is relatively simple example, I was unable find a clean method of doing this anywhere else, so I thought I would post it here.
As part of a file upload package, I wanted to prevent the uploading of double byte character filenames and other special ASCII characters that may not work well on a Windows and/or Linux system. Here is the statement I ended up using which seems to have done the trick.
Here is a fixed version of the UK postcode check function by tomas at phusis dot co dot uk. There was a bug on line 2 of the reg expression where a closing square-bracket was doubled-up («]]» which should’ve been «]»).
function IsPostcode ( $postcode ) <
$postcode = strtoupper ( str_replace ( chr ( 32 ), » , $postcode ));
if( ereg ( «^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ]28?)|»
. «(([A-PR-UWYZ][A-HK-Y]73?)|»
. «(([A-PR-UWYZ]5[A-HJKSTUW])|»
. «([A-PR-UWYZ][A-HK-Y]2[ABEHMNPRVWXY]))))»
. «1[ABD-HJLNP-UW-Z]<2>)$» , $postcode ))
return $postcode ;
else
return FALSE ;
>
?>
Here’s a function i’ve created to return an array of each substring searched in a string.
In reply to Francis,
I actually used this to validate a phone number. The one discrepancy I found is with patterns such as 503-555-1212, 503-5551212, [503]5551212, and every other pattern that does not have single whitespace or a dash as a delimiter, ereg() will return false when given your expression.
Based on your pattern, I came up with a more general and concise version making use of the dot meta-character:
$pattern = «^.?7<3>. 1<3>.?9<4>$»;
When passed to ereg(), it will return «true» so long as there is 10 digits, regardless of the delimiter chosen by the user.
[503] 5551212 //true
5035551212 //true
503+555 1212//true
There is undocumented behaviour for this command!
You cannot check for strings of 1-256 characters or longer.
For example, this will evaluate to true:
But this will give the error:
PHP Warning: ereg(): REG_BADBR
PHP version (on Windows XP):
PHP 5.2.5 (cli) (built: Nov 8 2007 23:18:51)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
This is a date regexp that I made to allow different combinations of month, day, and year. it’s rather long but it works.
yyyy-mm-dd, mm-dd-yyyy, dd-mm-yyyy
2007-02-05
12-25-2007
25-02-2007
2-5-2007
25-2-2007
2007-9-23
09-06-2007
09-23-2007
The above will check valid
Anything not in one of the combinations of dd,mm,yyyy formats above will fail.
these will also fail
2007-32-12
13-22-2007
0-1-2007
1-0-2007
Any sugestions on making it smaller and more efficients would be appreciated.
Save yourself some headache and time, don’t use the \d (digits) \w (alphanumeric) and \s (whitespace) short forms. Not only do they make the code less readable, they don’t seem to work with ereg.
Use 9, [A-Za-z0-9], [ \n\r\t] instead.
Since the regex example in this article is a bit on the complex side, I’ll throw in a simpler regex example:
Say you want to validate valid variable names:
// ^ in this context means that the regex is anchored
// to the beginning of the string.
//
// A single [xxx] means that a single letter must mach
// the criteria within
//
// The [xxx]* means that [xxx] can mach from zero to
// unlimited times.
//
// The $ is another anchor, except it is for the end of
// the sting.
// Valid names: «_», «hello1», «a_variable»
// Invalid names: «4number», «five-to», «one two», » space «
//Test it out:
$regx = $regx_valid_variable_name ;
$valid = array ( ‘_’ , ‘hello1’ , ‘a_variable’ );
$invalid = array ( ‘4number’ , ‘five-to’ , ‘one two’ , ‘ space ‘ );
foreach( $valid as $v )
echo ‘Valid ‘ .( ereg ( $regx , $v ) ? ‘yes’ : ‘no‘ ) . «: $v
\n» ;
foreach( $invalid as $v )
echo ‘Invalid ‘ .(! ereg ( $regx , $v ) ? ‘yes’ : ‘no‘ ) . «: $v
\n» ;
?>
Ok well someone else posted this but if didn’t work so I made my own.
I used this to check file names that are to be created on a server.
File names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), and dot(.) will be accepted.
File names beginning with anything but a-Z or 0-9 will be rejected.
File names containing anything other than above mentioned will also be rejected.
I could not find a definitive and 100% working function that validates the UK postcodes, so was forced to write one myself.
The authoritative source of information is
which I amended with the new postcode for Tristan da Cunha.
Here is the ugly beast (don’t wanna see regexp’s ever again):
function IsPostcode ( $postcode ) <
$postcode = strtoupper ( str_replace ( chr ( 32 ), » , $postcode ));
if( ereg ( «^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ]61?)|»
. «(([A-PR-UWYZ][A-HK-Y]]45?)|»
. «(([A-PR-UWYZ]2[A-HJKSTUW])|»
. «([A-PR-UWYZ][A-HK-Y]1[ABEHMNPRVWXY]))))»
. «1[ABD-HJLNP-UW-Z]<2>)$» , $postcode ))
return $postcode ;
else
return FALSE ;
>
?>
A common mistake seems to be trying to escape characters within a bracket
expression. Unlike the preg functions, backslash is always taken literally
within a bracket expression using the ereg functions. See
http://php.planetmirror.com/manual/en/function.eregi.php#57824
for more details.
Some of the posts here can be re-written to be much simpler.
16-Feb-2005 10:02
attempts to allow square brackets in a string with
^[a-zA-Z0-9 [.[.] [.].] ]<1,>$
Although this appears to work a less confusing means is
^[]a-zA-Z0-9[]<1,>$
The ] has to be the first character (after a possible ^) but the [ can be
anywhere as long as it is not in the middle of a range of course.
09-Apr-2005 11:52
Says that ereg(«hi[:space:]*bob», $string)
doesnt work in php 4 and to use preg_match() instead.
The above quoted use is incorrect it should be
( «hi[[:space:]]*bob» , $string ); ?>
I tested this with the following in php 4.3.3 and it works fine
//The hex codes are space, tab, line feed, vertical tab, form feed, carriage return
$whitespace = «\x20\x09\x0a\x0b\x0C\x0d» ;
$teststring = «hi» . $whitespace . «bob» ;
$result = ereg ( «hi[[:space:]]*bob» , $teststring , $arr );
echo ( ‘Matches ‘ . $result . ‘ characters’ );
//Prints Matches 11 characters
?>
23-May-2005 08:22
Says that ereg(«^[‘ A-Za-Z]+$», $cardName); will not work.
The fault with the above is the range a-Z the capital Z comes before small a
and so this will fail. The following works fine
= «John ‘Doe'» ;
$result = ereg ( «^[‘ A-Za-z]+$» , $cardname , $arr );
echo ( ‘Matches ‘ . $result . ‘ characters’ );
//Prints Matches 10 characters
?>
09-Sep-2005 11:01
Tries to escape with \ in a bracket expression
You cannot with ereg functions (preg you can) so
ereg(«^([-a-zA-Z0-9_\.\!@#\$&\*\+\=\|])*$» , $var)
should be
( «^([-a-zA-Z0-9_.!@#$&*+=|])*$» , $var ); ?>
After a lot of hard work I managed to create the following regular expression, which matches any HTML tag pair (i.e. opening and closing tag), as specified by tagname:
The expression is deliberately very forgiving of bad HTML — I wanted to match anything that could be reasonably accepted by a forgiving browser, rather than make it standards compliant. Whitespace is allowed between the tagname and the opening and closing tag symbols, and also between the / and the tagname for the closing tag.
For my own use, I have wrapped it in a function call, which you may find useful. Here it is with a few notes. I hope somebody finds it useful.
function ereg_MatchedHTMLTags ( $tagname ) <
return «^(.*)( $tagname (>|[^>]*>))(.*)( $tagname (>|[^>]*>))(.*)$» ;
>
Источник