可以使用 PHP 中的 preg_replace 函數來實現正則替換指定內容,只替換一次。該函數使用正則表達式來搜索字符串,並用指定的替換內容替換所有匹配項。
以下是一個示例代碼,用於將字符串中的第一個匹配項替換爲指定的內容:
$string = 'This is a test string.';
$pattern = '/is/';
$replacement = 'at';
$result = preg_replace($pattern, $replacement, $string, 1);
echo $result;在上面的代碼中,我們定義了一個字符串 $string,一個正則表達式 $pattern 和一個替換字符串 $replacement。然後,我們使用 preg_replace 函數來搜索 $string 中第一個匹配 $pattern 的地方,並用 $replacement 替換它。函數的第四個參數是可選的,用於指定替換的最大次數。在這個例子中,我們將其設置爲 1,以便只替換第一個匹配項。
輸出將是:That is a test string.,其中第一個 is 被替換爲了 at。