Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中用变量文本替换精确的变量字符串?_Php_Mysql_String_Function - Fatal编程技术网

在PHP中用变量文本替换精确的变量字符串?

在PHP中用变量文本替换精确的变量字符串?,php,mysql,string,function,Php,Mysql,String,Function,我正在开发一个类似于Twitter的回复系统。 在字符串中有一段文本,其中id是可变的,例如:14&,138&,这取决于您的回复对象。 如何在字符串中找到14&,并将其替换为14& 这就是它的样子: 14& this is a reply to the comment with id 14 它应该是这样的: <u>14&</u> this is a reply to the comment with id 14 14&这是对id为14的评论的回复 如

我正在开发一个类似于Twitter的回复系统。
在字符串中有一段文本,其中id是可变的,例如:
14&
138&
,这取决于您的回复对象。
如何在字符串中找到
14&
,并将其替换为
14&

这就是它的样子:

14& this is a reply to the comment with id 14
它应该是这样的:

<u>14&</u> this is a reply to the comment with id 14
14&这是对id为14的评论的回复

如何在PHP中实现这一点?提前谢谢

如果您知道ID,很简单:

<?php
  $tweet_id = '14';
  $replaced = str_replace("{$tweet_id}&", "<u>{$tweet_id.}&</u>", $original);

如果您知道ID,那么很简单:

<?php
  $tweet_id = '14';
  $replaced = str_replace("{$tweet_id}&", "<u>{$tweet_id.}&</u>", $original);

将正则表达式与函数一起使用

<?php

$str = '14& this is a reply to the comment with id 14';
echo preg_replace('(\d+&)', '<u>$0</u>', $str);

将正则表达式与函数一起使用

<?php

$str = '14& this is a reply to the comment with id 14';
echo preg_replace('(\d+&)', '<u>$0</u>', $str);

产出:

string '<u>14&</u> this is a reply to the comment with id 14' (length=52)
string '<u>14</u> this is a reply to the comment with id 14' (length=51)
string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66)
产出:

string '<u>14&</u> this is a reply to the comment with id 14' (length=52)
string '<u>14</u> this is a reply to the comment with id 14' (length=51)
string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66)
string'是对id为14'(长度=66)的注释的回复
产出:

string '<u>14&</u> this is a reply to the comment with id 14' (length=52)
string '<u>14</u> this is a reply to the comment with id 14' (length=51)
string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66)
产出:

string '<u>14&</u> this is a reply to the comment with id 14' (length=52)
string '<u>14</u> this is a reply to the comment with id 14' (length=51)
string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66)
string'是对id为14'(长度=66)的注释的回复

space,任意大小的数字&然后空格-正确吗?@Dagon是的,正确。:)您是否希望它也替换下面的3和4,还是应该排除它们<代码>1&在开头。2和中间。3&后面跟着一个词。和4&前面有一个单词。最后以5结尾&
?空格,任意大小的数字&然后是空格-正确吗?@Dagon是的,正确。:)您是否希望它也替换下面的3和4,还是应该排除它们<代码>1&在开头。2和中间。3&后面跟着一个词。和4&前面有一个单词。最后以5结尾&
?我扩展了我的答案:它使用我扩展了我的答案:它使用