분류 php

PHP의 내장 preg_ * 함수를 위한 깔끔한 인터페이스

컨텐츠 정보

  • 조회 272 (작성일 )

본문

내장 된 preg_ * 함수에는 참조로 변수를 전달하고 거짓 또는 널 값을 오류로 처리하는 등의 이상한 패턴이 필요합니다. 

spatie / regex는 preg_match, preg_match_all, preg_replace 및 preg_replace_callback을 위한 깔끔한 인터페이스를 제공합니다.


https://github.com/spatie/regex 


https://murze.be/2016/08/package-easily-work-regex-php/


use Spatie\Regex\Regex;

// Using `match`
Regex::match('/a/', 'abc'); // `MatchResult` object
Regex::match('/a/', 'abc')->hasMatch(); // true
Regex::match('/a/', 'abc')->result(); // 'a'

// Capturing groups with `match`
Regex::match('/a(b)/', 'abc')->result(); // 'ab'
Regex::match('/a(b)/', 'abc')->group(1); // 'b'

// Setting defaults
Regex::match('/a(b)/', 'xyz')->resultOr('default'); // 'default'
Regex::match('/a(b)/', 'xyz')->groupOr(1, 'default'); // 'default'

// Using `matchAll`
Regex::matchAll('/a/', 'abcabc')->hasMatch(); // true
Regex::matchAll('/a/', 'abcabc')->results(); // Array of `MatchResult` objects

// Using replace
Regex::replace('/a/', 'b', 'abc')->result(); // 'bbc';
Regex::replace('/a/', function (MatchResult $result) {
    return $result->result() . 'Hello!';
}, 'abc')->result(); // 'aHello!bc';



Spatie는 벨기에 앤트워프에 본사를 둔 웹 디자인 대행사입니다. 당사 웹 사이트에서 모든 오픈 소스 프로젝트에 대한 개요를 확인할 수 있습니다.