[英]How to modify a word in a sentence using regex to find the word in php
I have a sentence with words/equations in it that start and end with $.我有一个句子,其中包含以 $ 开头和结尾的单词/方程式。 For example,例如,
"The $girl$ is a $good$ person"
I want to modify the sentence to我想将句子修改为
"The $$girl$$ is a $$good$$ person".
I have found a way to find the words but how to replace them with the modified version of themselves is the issue.我找到了一种查找单词的方法,但问题是如何用修改后的版本替换它们。 I found this on this platform but it doesn't answer the question.我在这个平台上找到了这个,但它没有回答这个问题。
preg_replace('/\$\S+\$/', '', $text)
Any help will be appreciated.任何帮助将不胜感激。 Thanks谢谢
You can use您可以使用
$text = 'The $girl$ is a $good$ person';
echo preg_replace('/\$[^\s$]+\$/', '\$$0\$', $text);
// => The $$girl$$ is a $$good$$ person
See the PHP demo .请参阅PHP 演示。 See this regex demo .请参阅此正则表达式演示。 Details :详情:
\$
- a $
literal char \$
- 一个$
文字字符[^\s$]+
- any one or more chars other than $
and whitespace [^\s$]+
- 除了$
和空格之外的任何一个或多个字符\$
- a $
literal char. \$
- $
文字字符。 The \$$0\$
replacement means the whole match is replaced with itself ( $0
) and two $
are added on both ends. \$$0\$
替换意味着整个匹配被替换为自身( $0
)并在两端添加两个$
。
To avoid re-wrapping $$...$$
substrings, you can use为避免重新包装$$...$$
子字符串,您可以使用
$text = 'The $girl$ is a $good$ person, and keep $$this$$.';
echo preg_replace('/\${2,}[^\s$]+\${2,}(*SKIP)(*FAIL)|\$[^\s$]+\$/', '\$$0\$', $text);
// => The $$girl$$ is a $$good$$ person, and keep $$this$$.
See this PHP demo .请参阅此 PHP 演示。 The \${2,}[^\s$]+\${2,}(*SKIP)(*FAIL)|
\${2,}[^\s$]+\${2,}(*SKIP)(*FAIL)|
part matches all substrings not containing $
and whitespace between two or more $
chars and skips them. part 匹配所有不包含$
和两个或多个$
字符之间的空格的子字符串并跳过它们。
See the regex demo .请参阅正则表达式演示。
You can assert whitespace boundaries around the pattern and use the full match using $0
around dollar signs.您可以在模式周围声明空白边界,并在美元符号周围使用$0
来使用完全匹配。
Note that \S
can also match $
so you could use a negated character class [^$]
to match any character except the $
请注意, \S
也可以匹配$
,因此您可以使用否定字符 class [^$]
匹配除$
之外的任何字符
(?<!\S)\$[^$]+\$(?!\S)
(?<!\S)
Assert a whitespace boundary to the left (?<!\S)
向左断言空白边界\$
Match $
\$
匹配$
[^$]+
Match 1+ occurrences of any char except $
[^$]+
匹配 1+ 个除$
之外的任何字符\$
Match $
\$
匹配$
(?!\S)
Assert a whitespace boundary to the right (?!\S)
断言右边的空白边界See a regex demo and a PHP demo .请参阅正则表达式演示和PHP 演示。
$text = '"The $girl$ is a $good$ person"';
echo preg_replace('/(?<!\S)\$[^$]+\$(?!\S)/', '$$0$', $text);
Output Output
The $$girl$$ is a $$good$$ person
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.