如何仅在 php 中被白色 space 包围时替换文本

How to replace text only if surrounded by white space in php

我正在尝试创建一个表单,用户可以提交该表单并使用它来查找和替换长字符串中的文本。但是,我要替换的许多字符串只有 2-3 个字母(例如 "od"、"ph"),通常出现在单词中间。我想遍历我正在搜索的所有短语,并且只有在字符串前有白色 space 时才替换它们,以避免替换单词中间的字符串。有什么想法吗?

if(isset($_POST["text"]))
{
    $original = $_POST["text"];
    $abbreviation= array();
    $abbreviation[0] = 'od';
    $abbreviation[1] = 'rn';        
    $abbreviation[2] = 'ph';
    $abbreviation[3] = 'real';  
    $translated= array();
    $translated[0] ='odometer';
    $translated[1] ='run';
    $translated[2] ='pinhole';
    $translated[3] ='fake';
    $newtext=  str_ireplace ($abbreviation, $translated ,$original);
    echo nl2br(htmlspecialchars($newnote));
}

您可以在两侧使用单词边界断言 (\b) 将缩写词视为单独的单词:

preg_replace('/\bod\b/i', 'odometer', 'od test od test od.')
// "odometer test odometer test odometer."

如果您只想在字符串周围有空格时匹配,请使用后向断言 ((?<=) 和先行断言 ((?=) 匹配空格 (\s) :

preg_replace('/(^|(?<=\s))od((?=\s)|$)/i', 'odometer', 'od test od test od.')
// "odometer test odometer test od."

请注意跟踪期间的处理方式不同。 (另请注意,preg_replace 可以将多个 pattern/replacement 映射作为数组。)

来自docs

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

\w\W指的是"word"和"non-word"字符:

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.