[英]Remove text after link
因此,我在网站上有一个@mentions
函数,用户可以自己输入,但可以执行以下操作:
@foo您好,其中包括一些提及文字。
我只想删除文本(@foo之后的所有内容),内容通过streamitem_content
:
$json['streamitem_content_usertagged'] =
preg_replace('/(^|\s)@(\w+)/', '\1@<a href="profile.php?username=$1">$1</a>',
$json['streamitem_content']);
试试这个
$json['streamitem_content'] = '@foo Hello This is some mention text included.';
$json['streamitem_content_usertagged'] =
preg_replace('/@(\w+)/', '@<a href="profile.php?username=$1">$1</a>',
$json['streamitem_content']);
echo $json['streamitem_content_usertagged'];
输出:
@<a href="profile.php?username=foo">foo</a> Hello This is some mention text included.
Preg_replace
只会替换找到的内容,因此您不需要查找不感兴趣的内容。 如果您确实想捕获字符串的多个部分,尽管捕获组在每个group ()
之后增加一个。 所以这
preg_replace('/(^|\s)@(\w+)/', '$1@<a href="profile.php?username=$2">$2</a>',
$json['streamitem_content']);
echo $json['streamitem_content_usertagged'];
实际上是
preg_replace('/(^|\s)@(\w+)/', '$1@<a href="profile.php?username=$2">$2</a>',
$json['streamitem_content']);
更新:
$json['streamitem_content'] = '@foo Hello This is some mention text included.';
$json['streamitem_content_usertagged'] =
preg_replace('/@(\w+).*$/', '@<a href="profile.php?username=$1">$1</a>',
$json['streamitem_content']);
echo $json['streamitem_content_usertagged'];
输出:
@<a href="profile.php?username=foo">foo</a>
如果您要在@foo
之后替换的内容可以扩展为多行,请使用s
修饰符 。
Regex101演示: https ://regex101.com/r/tX1rO0/1
正则表达式几乎说“ @
然后捕获所有连续的a-zA-Z0-9_
字符。 在那些连续字符之后,我们不在乎到字符串的末尾。
您可以使用此:
preg_replace('/^\s*@(\w+)/', '<a href="profile.php?username=$1">@$1</a>',
$json['streamitem_content']);
这将删除前导空格,并在超链接的文本中(而非链接参数)包含@。
如果您需要保持领先的空白处:
preg_replace('/^(\s*)@(\w+)/', '$1<a href="profile.php?username=$2">@$2</a>',
$json['streamitem_content']);
您可以使用explode();
和str_replace();
。 他们可能比preg
有速度优势。
假设该行可用作变量(例如$mention
):
$mention = $json['streamitem_content'];
$mention_parts = explode(" ", $mention);
$the_part_you_want = str_replace('@','', $mention_parts[0]);
// or you could use $the_part_you_want = ltrim($mention_parts[0], '@');
$json['streamitem_content_usertagged'] = '@<a href="profile.php?username=' . $the_part_you_want . '">' . $mention_parts[0] . '</a>';
或使用trim($mention_parts[0]);
如果不需要,请删除任何空格。
您可以使用更少的变量并将$mention
作为数组重用,但这似乎是阐明原理的更清晰方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.