>  기사  >  백엔드 개발  >  PHP preg_replace()

PHP preg_replace()

PHPz
PHPz원래의
2024-08-29 12:49:57539검색

PHP preg_replace() 함수는 PHP 프로그래밍 언어에 내장된 함수입니다. Preg_replace() 함수는 콘텐츠 검색 및 바꾸기를 위한 정규식을 수행하는 데 도움이 됩니다. 배열 인덱스 값 내부에 있는 단일 문자열 또는 여러 문자열 요소에 대해 교체를 수행할 수 있습니다. 이는 어느 정도 preg_match()와 유사하지만 preg_replace()에서는 문자열에 대한 패턴 일치를 수행한 후 문자열 요소/요소 교체가 특정 텍스트에 대해 수행됩니다. 이것은 문자열 내용을 조작하기 위한 PHP 프로그래밍 언어의 중요한 정규식 중 하나입니다. preg_replace()에 대해서는 아래에서 간략하게 설명하겠습니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

다음은 구문입니다.

preg_replace( $pattern1, $replacement1, $subject1, $limit1, $count1 )

매개변수

preg_replace() 함수는 일반적으로 위에서 언급한 대로 주로 5개의 매개변수를 받습니다. $pattern1, $replacement1, $subject1, $limit1 및 $count1 매개변수입니다.

아래의 간략한 설명과 함께 이러한 매개변수에 대해 알아보세요.

  • $pattern1: preg_replace() 함수의 $pattern1 매개변수에는 콘텐츠 검색에 도움이 되는 문자열 요소가 포함되어 있습니다. 단일 문자열 값이거나 문자열/문자열의 배열일 수 있습니다.
  • Sreplacement1: preg_replace() 함수의 $replacement1 매개변수는 필수 매개변수입니다. 문자열을 지정하거나 대체할 문자열이 포함된 문자열 배열을 지정하는 것이 도움이 됩니다. 이 매개변수에 문자열 값이 있는 경우, Pattern1 매개변수는 배열이 되고 모든 패턴/패턴은 해당 특정 문자열로 대체됩니다. replacement1과 Pattern1 매개변수가 모두 배열이면 모든 Pattern1이 replacement1 대응 항목으로 대체됩니다. replacement1이 배열이고 패턴1 배열보다 적은 수의 요소로 구성된 경우 추가 패턴은 단순한 빈 문자열로 대체됩니다.
  • $subject1: preg_replace() 함수의 $subject1 매개변수는 $pattern 변수의 문자열 값에서 문자열 내용을 검색하고 바꾸는 데 사용되는 문자열 또는 문자열 배열입니다.
  • $limit1: preg_replace() 함수의 $limit 매개변수는 매우 중요하며 모든 패턴에 대해 가능한 대체를 최대로 지정합니다.
  • $count1: preg_replace() 함수의 $count 매개변수는 일반적으로 선택적 매개변수입니다. 이 매개변수의 변수 값은 원래 문자열에서 수행된 대체 횟수를 나타내는 숫자로 채워집니다.

preg_replace() 함수의 반환 값: preg_replace() 함수는 subect1 매개변수가 배열/문자열인 경우에만 배열을 반환합니다.

PHP preg_replace() 함수는 어떻게 작동하나요?

PHP 프로그래밍 언어의 Preg_replace() 함수는 내부에 언급된 매개변수를 기반으로 작동합니다. 주로 검색 시 사용되는 원래 문자열을 사용하고 문자열/문자열을 바꾸는 방식으로 작동합니다. 다른 매개 변수는 그다지 중요하지 않을 수 있습니다. Preg_replace()는 각 일치 항목을 두 번째nd 매개변수로 바꾸는 데 사용되는 매개변수(첫 번째 매개변수)이므로 정규 표현식을 사용합니다. 두 번째 매개변수는 일반 텍스트이고, 세 번째rd 매개변수는 작동할 문자열입니다. 세 번째 매개변수에는 정규식 규칙의 일부로 일치하는 텍스트를 삽입하는 $n이 포함될 수 있습니다. 복잡한 다중 부분 정규식을 작성하는 경우. 일치하는 텍스트를 사용하려면 $0을 사용할 수 있습니다. 아래 예시 2를 통해 알 수 있도록 예시를 확인해 보세요.

PHP에서 preg_replace() 함수를 구현하는 예

다음은 언급된 몇 가지 예입니다.

예시 #1

아래 예에서는 "Copyright 1998" 값으로 "$copy_date1" 변수를 생성한 후 preg_replace() 함수를 값으로 사용하여 동일한 변수를 생성합니다. 따라서 preg_replace() 함수의 결과는 “$copy_date1” 변수에 저장됩니다. preg_replace() 함수 내에서 0-9(모두) 값은 문자열 값 "2020"으로 대체되고 "$copy_date1" 변수에 저장됩니다. 그러면 "$copy_date1"에 있는 값이 변경된 문자열로 인쇄됩니다. 그러면 "Copyright 2020"이 출력에 인쇄됩니다.

코드:

<?php
$copy_date1 = "Copyright 1998";
$copy_date1 = preg_replace("([0-9]+)", "2020", $copy_date1);
print $copy_date1;
?>

출력:

PHP preg_replace()

Example #2

In the below example, a variable “$a1” is created with the string value “Fool bool tool fool”. Then again the same naming variable is created with the preg_replace() function. In the preg_replace() string value is used to search which are ending with a cool after any alphabet. If there is anything then those string values will be printed one by one after the “Got word:” word. And this result will be stored in the “$a1” variable. Then the word will be printed using the print function.

Code:

<?php
$a1 = "Foo mool bool tool fool";
$a1 = preg_replace("/[A-Za-z]ool\b/", "Got word: $0 \n", $a1);
print $a1;
?>

Output:

PHP preg_replace()

Example #3

In the below example, the date will be changed in the string value as mentioned in the replacement1 term. At first a variable “$date1” is created inside of the PHP tags with the value “Sep 29, 2020”. Then the “$pattern1” variable is created with meta-characters that are used to find a word in the character. Then the “$replacement1” variable is created with the value ”${1} 6, $3”. Here “1” inside flower braces will remain the same and then in the 2nd value 6 will be replaced in the place of 29 and $3 represents the 3 string elements inside of the array. If “$1 ” is placed then only Sep will be printed if the $2 is represented then replaced value only 6 will be printed. So the $3 is mentioned to mention all the 3 elements which are to be printed using echo function.

Code:

<?php
$date1 = 'Sep 29, 2020';
$pattern1 = '/(\w+) (\d+), (\d+)/i';
$replacement1 = '${1} 6,$3';
echo preg_replace($pattern1, $replacement1, $date1);
?>

Output:

PHP preg_replace()

Example #4

In the below example, multiple string elements are replaced using the array function with the single string values in the index values to change. At first “string1” variable is created with a string sentence with many words. Then “$patterns1” variable is created with array() function as variable. Then inside of the $patterns[index value] is/are stored with a different string that is already present in the original string. Similarly the same is done for the “$replacements1” variable with different string values to change the list of strings inside of the string sentence. Then “$newstr1” variable is created with the value as preg_replace() function. Then echo function is used to print the changed string sentence. Check out this in the output image.

Code:

<?php
$string1 = 'The fast black tiger runs away from the zoo.';
$patterns1 = array();
$patterns1[0] = '/fast/';
$patterns1[1] = '/black/';
$patterns1[2] = '/tiger/';
$replacements1 = array();
$replacements1[2] = 'Slow';
$replacements1[1] = 'Elephant';
$replacements1[0] = 'Jumped and';
$newstr1 = preg_replace($patterns1, $replacements1, $string1);
echo "<b>The String after the replacements:</b> " .$newstr1;
?>

Output:

PHP preg_replace()

Conclusion

I hope you understood what is the definition of PHP preg_replace() function with its syntax along with various parameter explanation, How preg_replace() function works along with the various examples to implement preg_replace() function in PHP Programming language.

위 내용은 PHP preg_replace()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.