suche nach in der

eregi_replace> <ereg_replace
Last updated: Fri, 18 May 2012

view this page in

ereg

(PHP 4, PHP 5)

eregSucht Übereinstimmungen mit einem regulären Ausdruck

Beschreibung

int ereg ( string $pattern , string $string [, array &$regs ] )

Sucht in string unter Berücksichtigung der Groß- und Kleinschreibung nach Übereinstimmungen mit dem regulären Ausdruck, der in pattern angegeben wurde.

Warnung

Diese Funktion ist seit PHP 5.3.0 DEPRECATED (veraltet). Sich auf diese Funktion zu verlassen ist in keiner Weise empfehlenswert.

Parameter-Liste

pattern

Regulärer Ausdruck mit Berücksichtigung der Groß- und Kleinschreibung

string

Die zu durchsuchende Zeichenkette

regs

Wenn Übereinstimmungen mit eingeklammerten Teilzeichenketten von pattern gefunden werden und die Funktion mit dem dritten Argument regs aufgerufen wurde, werden die Übereinstimmungen in den Elementen des Arrays regs gespeichert.

$regs[1] enthält die Teilzeichenkette der ersten Klammer, $regs[2] die Teilzeichenkette der zweiten usw. $regs[0] enthält bei Übereinstimmung mit string eine Kopie der kompletten Zeichenkette string.

Rückgabewerte

Gibt die Länge der übereinstimmenden Zeichenkette zurück, falls in string eine Übereinstimmung mit pattern gefunden wurde oder FALSE, wenn keine Übereinstimmung gefunden wurde oder wenn ein Fehler aufgetreten ist.

Falls der optionale Parameter regs nicht übergeben wurde oder die Länge der übereinstimmenden Zeichenkette 0 ist, gibt diese Funktion 1 zurück.

Changelog

Version Beschreibung
4.1.0 Bis (und inklusive) PHP 4.1.0 wird $regs mit genau zehn Elementen gefüllt, auch wenn es tatsächlich mehr oder weniger Übereinstimmungen mit den eingeklammerten Teilzeichenketten gibt. Dies wirkt sich aber nicht auf ereg()s Fähigkeit aus, mehr übereinstimmende Teilzeichenketten zu finden. Falls keine Übereinstimmungen gefunden werden, wird $regs nicht von ereg() verändert.

Beispiele

Beispiel #1 ereg()-Beispiel

Das folgende Code-Schnipsel mimmt ein Datum im ISO-Format (JJJJ-MM-TT) und gibt es im Format TT.MM.JJJJ aus:

<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"$date$regs)) {
    echo 
"$regs[3].$regs[2].$regs[1]";
} else {
    echo 
"Ungültiges Datumsformat: $date";
}
?>

Anmerkungen

Hinweis:

Seit PHP 5.3.0 ist die regex-Erweiterung zugunsten der PCRE-Erweiterung als veraltete markiert. Ein Aufruf dieser Funktion wird eine E_DEPRECATED-Notice ausgeben. Sie können sich die Liste der Unterschiede ansehen, wenn Sie Hilfe beim Umstieg auf PCRE benötigen.

Hinweis:

Die Funktion preg_match(), die eine zu Perl kompatible Syntax regulärer Ausdrücke verwendet, ist häufig die schnellere Alternative zu ereg().

Siehe auch

  • eregi() - Sucht Übereinstimmung mit regulärem Ausdruck ohne Berücksichtigung von Groß-/Kleinschreibung
  • ereg_replace() - Ersetzt einen regulären Ausdruck
  • eregi_replace() - Ersetzt einen regulären Ausdrück ohne Berücksichtigung von Groß-/Kleinschreibung
  • preg_match() - Führt eine Suche mit einem regulären Ausdruck durch
  • strpos() - Sucht das erste Vorkommen des Suchstrings
  • strstr() - Findet das erste Vorkommen eines Strings
  • quotemeta() - Quoten von Meta-Zeichen



add a note add a note User Contributed Notes
ereg
notbald at gmail spam away com
11-Jul-2007 10:26
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 [0-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:

<?php
$regex_valid_variable_name
= '^[A-Za-z_][A-Za-z0-9_]*$';

// ^ 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' : '<b>no</b>') . ": $v<br />\n";

foreach(
$invalid as $v)
    echo
'Invalid '.(!ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";
?>
ben at agaricdesign dot com
10-Jun-2007 12:49
Here is a tutorial on regular expressions in PHP, which I needed to create ereg functions not covered in the snippets:

http://www.zend.com/zend/spotlight/code-gallery-wade5.php
jaik at fluidcreativity dot co dot uk
31-Aug-2006 05:41
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 "]").

<?php
function IsPostcode($postcode) {
 
$postcode = strtoupper(str_replace(chr(32),'',$postcode));
  if(
ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
   return
$postcode;
  else
   return
FALSE;
}
?>
theppg_001 at hotmail dot com
19-Aug-2006 04:00
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.

Here it is.
<?php
$result
= ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$" , $filename);
?>
tomas at phusis dot co dot uk
06-Jun-2006 05:41
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

http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm

which I amended with the new postcode for Tristan da Cunha.

Here is the ugly beast (don't wanna see regexp's ever again):

<?php
function IsPostcode($postcode) {
 
$postcode = strtoupper(str_replace(chr(32),'',$postcode));
  if(
ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y]][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
    return
$postcode;
  else
    return
FALSE;
}
?>
'morgan'.'galpin'.chr(64).'gmail'.'.com'
11-May-2006 10:16
Try this version instead of the one previously posted.

<?php
 
/**
    Returns an array containing each of the sub-strings from text that
    are between openingMarker and closingMarker. The text from
    openingMarker and closingMarker are not included in the result.
    This function does not support nesting of markers.
  */
 
function returnSubstrings($text, $openingMarker, $closingMarker) {
   
$openingMarkerLength = strlen($openingMarker);
   
$closingMarkerLength = strlen($closingMarker);

   
$result = array();
   
$position = 0;
    while ((
$position = strpos($text, $openingMarker, $position)) !== false) {
     
$position += $openingMarkerLength;
      if ((
$closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
       
$result[] = substr($text, $position, $closingMarkerPosition - $position);
       
$position = $closingMarkerPosition + $closingMarkerLength;
      }
    }
    return
$result;
  }
 
 
// Example:
 
$exampleText = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";
 
$result = returnSubstrings($exampleText, "<b>", "</b>");
 
var_export($result);
 
 
// Prints:
  // array (
  //   0 => 'bonjour',
  //   1 => 'comment',
  // )
?>
info at orgied dot com
21-Mar-2006 03:54
Here's a function i've created to return an array of each substring searched in a string.

<?
function Return_Substrings($text, $sopener, $scloser)
                {
               
$result = array();
               
               
$noresult = substr_count($text, $sopener);
               
$ncresult = substr_count($text, $scloser);
               
                if (
$noresult < $ncresult)
                       
$nresult = $noresult;
                else
                       
$nresult = $ncresult;
       
                unset(
$noresult);
                unset(
$ncresult);
               
                for (
$i=0;$i<$nresult;$i++)
                        {
                       
$pos = strpos($text, $sopener) + strlen($sopener);
               
                       
$text = substr($text, $pos, strlen($text));
               
                       
$pos = strpos($text, $scloser);
                       
                       
$result[] = substr($text, 0, $pos);

                       
$text = substr($text, $pos + strlen($scloser), strlen($text));
                        }
                       
                return
$result;
                }
?>

Example :

<?
    $string
= "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";

   
$result = Return_Substrings($string, "<b>", "</b>");
?>
psonice (aat) gmail.com
14-Mar-2006 10:39
I wanted a more strict check for UK postcodes, and decided to do it by stripping all whitespace then using ereg:

<?php
$pcode
=str_replace(" ","",$in_post_code);
if (!
ereg('^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]{0,1}[0-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.
ar_cat at shaw dot ca
15-Dec-2005 12:13
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.

^[+-]?[0-9]*\.?[0-9]+$

/*
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 :)
net_navard at yahoo dot com
15-Nov-2005 04:35
Hello

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

With regards

Amir Hossein Estakhrian
Jason Smart knarlin at yahoo dot com dot au
16-Oct-2005 10:13
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
<?php ereg("hi[[:space:]]*bob", $string); ?>

I tested this with the following in php 4.3.3 and it works fine
<?php
//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
<?php
$cardname
= "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
<?php ereg("^([-a-zA-Z0-9_.!@#$&*+=|])*$", $var); ?>
puremango dot co dot uk at gmail dot com
19-Jul-2005 03:34
for constructing regexes, I recommend

http://www.weitz.de/regex-coach/

-it highlights the match as you type it!!!
Joel Weierman
22-Jun-2005 09:56
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.

ereg("[^a-zA-Z0-9._-]", $file_name)
irlkersten at gmail dot com
22-Jun-2005 08:54
On a small note to email checking:
Recently it is possible to register domains like www.küche.de

This would also mean that the IsEMail() function from "php at easy2sync dot com" would report an email address like "contact@küche.de" as false.

To correct this, use the function below:

function IsEMail($e)
{
    if(eregi("^[a-zA-Z0-9]+[_a-zA-Z0-9-]*
(\.[_a-z0-9-]+)*@[a-zöäüÖÄÜ0-9]+
(-[a-zöäüÖÄÜ0-9]+)*(\.[a-zöäüÖÄÜ0-9-]+)*
(\.[a-z]{2,4})$", $e))
    {
        return TRUE;
    }
    return FALSE;
}
php at REMOVEMEkennel17 dot co dot uk
27-Apr-2005 04:00
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:

^(.*)(<[ \n\r\t]*tagname(>|[^>]*>))(.*)(<[ \n\r\t]*/[ \n\r\t]*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.

- Mark Clements

<?php

function ereg_MatchedHTMLTags($tagname) {
    return
"^(.*)(<[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)(<[ \\n\\r\\t]*/[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)$";
}

// Use with eregi to ensure case-insensitive match.
//        e.g. to split an HTML page based on body tag:
//             eregi(ereg_MatchedHTMLTags('body'), $Source, $Matches)

// The following values will be held in $Matches
//(marked values are unintended byproducts of the expression)
//           *[0] - the entire string ($Source).
//            [1] - everything before the opening tag
//            [2] - the opening tag, including all contents (i.e. everything between < and >)
//           *[3] - the opening tag from end of the tag name,
//                      e.g. '<body bgcolor="#000000">' gives ' bgcolor="#000000">'
//            [4] - the tag contents (everything between the opening and closing tag)
//            [5] - the complete closing tag.
//           *[6] - the closing tag from the end of the tag name
//                      e.g. '</body invalid text>' gives ' invalid text>'
//            [7] - everything after the closing tag.

?>

eregi_replace> <ereg_replace
Last updated: Fri, 18 May 2012