目前,我有以下代碼,它用於執行模式匹配&模式替換。如何通過僅使用preg_replace來檢查模式是否匹配
<?php
function fun($text) {
if (preg_match("/^(ATE|EAT)\s+(\S+).*/", $text)) {
$text = preg_replace("/^(ATE|EAT)\s+(\S+).*/", "EAT $2", $text);
} else {
$text = preg_replace("/.*(ATE|EAT).*/", "EAT", $text);
}
return $text;
}
// EAT pizza
echo fun('EAT pizza') . "\n";
// EAT pizza
echo fun('EAT pizza at paris') . "\n";
// EAT
echo fun('I EAT pizza at paris') . "\n";
我覺得上面的代碼沒有經過優化,因爲我preg_replace
之前執行preg_match
。我覺得這是多餘的。
我試圖從preg_replace
<?php
function fun($text) {
$tmp = preg_replace("/^(ATE|EAT)\s+(\S+).*/", "EAT $2", $text);
// I don't think this is the correct way to check for "Not Match" ?!
if ($tmp === $text) {
$tmp = preg_replace("/.*(ATE|EAT).*/", "EAT", $text);
}
return $tmp;
}
// EAT pizza
echo fun('EAT pizza') . "\n";
// EAT pizza
echo fun('EAT pizza at paris') . "\n";
// EAT
echo fun('I EAT pizza at paris') . "\n";
然而,fun('EAT pizza')
檢查返回的字符串會失敗,因爲它會打印出EAT
,而不是預期的EAT pizza
。
有沒有正確的方法來優化上述代碼?
什麼是你想實現你的功能?如果你總是希望這個字符串是「EAT pizza」,那麼只要preg_match爲true就設置它。 – karlingen