删除链接后的文本


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只会替换它找到的内容,所以你不需要找到你不感兴趣的内容。如果您确实想捕获字符串的多个部分,则捕获组在每组()之后增加一个。所以这个

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

所以regex几乎说找到一个@,然后捕获所有连续的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>';

或者使用CCD_ 13来去除任何不需要的空白。

您可以使用更少的变量并将$mention重新用作数组,但这似乎是一种更清晰的方式来说明原理。