英文:
How to replace the value of a string within two characters in php
问题
早上好,大家,
我需要找出是否有一种方法可以更改 * * 内的值。
示例:
大家好,这是我的第一篇帖子。
*photo1*
*photo2*
*photo3*
很快见...
并将代码替换为:
大家好,这是我的第一篇帖子。
*photo*
*photo*
*photo*
很快见...
在单词 "photo" 后面没有数字
当前的工作方式:
我有一个包含在星号之间的单词 "photo1"、"photo2"、"photo3" 的文本文件。通过 file_get_contents 命令读取此文件,我需要删除单词 "photo" 末尾的数字。
英文:
Good morning everyone,
I need to figure out if there is a way to change the values inside the * *.
Example:
Hello everyone, this is my 1st post.
*photo1*
*photo2*
*photo3*
See you soon...
and replace the code with:
Hello everyone, this is my 1st post.
*photo*
*photo*
*photo*
See you soon...
without number after the word photo
How it works currently:
I have a txt file that contains the words photo1, photo2, photo3 between asterisks. This file is read via the file_get_contents command and I would need to remove the number at the end of the word photo.
答案1
得分: 1
你可以使用 preg_replace
来实现这个。例如:
$str = ''*photo9*';
echo preg_replace(''/\*photo[0-9]+\*/'', ''photo'', $str);
输出:
> photo
注意:\
是为了转义表达式中的星号 *
,因为没有转义它的话,它会具有特殊含义 - 你需要匹配字面上的星号。
这可能更简单(取决于你想要做什么):
echo preg_replace(''/\d/'', '''', $str);
注意:\d
代表数字,将匹配从 0-9
的数字。更简洁的等价表达式是 /[0-9]+/
- +
意味着必须是一个或多个字符是数字。
英文:
You can use preg_replace
for that. E.g:
$str = '*photo9*';
echo preg_replace('/\*photo[0-9]+\*/', 'photo', $str);
Output:
> photo
Note. \
is to escape the asterisk *
in the expression, because it has a special meaning without it – you need to match the literal asterisk.
This may be more simple (depending on what you are trying to do):
echo preg_replace('/\d/', '', $str);
Note. \d
stands for digit, and will target numerals from 0-9
. A more concise equivalent would be /[0-9]+/
– The +
means "one or more" characters must be a digit.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论