PHP 正则表达式 - 删除之后的字符

发布于 2024-12-21 10:47:21 字数 375 浏览 0 评论 0原文

我有类似的 PHP 字符串

$str1 = "hello ... this is the rest of the line"

,或者

$str1 = "ASDFDF ... this is also the rest of the line";

我正在尝试纠正一个正则表达式语句,该语句将在字符串中出现“...”后提取文本。我无法可靠地做到这一点......

所以在上述情况下,我想......

 $extract = "这是该行的其余部分";

...你明白了。

I have PHP strings like

$str1 = "hello ... this is the rest of the line"

or

$str1 = "ASDFDF ... this is also the rest of the line";

I am trying to right a regex statement that will extract the text after "..." appears in the string. I am not able to do this reliably..

so in the above cases, i want to...

 $extract = "this is the rest of the line";

... you get the point.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柏拉图鍀咏恒 2024-12-28 10:47:21

为什么使用正则表达式?只需分解字符串并选取结果中的第二个元素:

$str = "hello ... this is the rest of the line";
list(, $rest) = explode(" ... ", $str, 2) + array(, '');

这基本上是相同的事情,并且正则表达式并不更快。

Why use regex? Just explode the string and pick up the second element in the result:

$str = "hello ... this is the rest of the line";
list(, $rest) = explode(" ... ", $str, 2) + array(, '');

It's basically the same thing, and the regex for this is no faster.

﹏半生如梦愿梦如真 2024-12-28 10:47:21

有多种方法可以做到这一点。

使用 strpos 和 substr:

function rest_of_line($line){
  $loc = strpos($line, '...');
  if($loc !== FALSE){
      return substr($line, $loc+3);
  }
  return $line;
}

$str1 = "hello ... this is the rest of the line";
$str2 = "ASDFDF ... this is also the rest of the line";
echo rest_of_line($str1);
echo rest_of_line($str2);

或使用explode:

$rest = explode('...', $str1, 2); // the 2 ensures that only the first occurrence of ... actually matters.
echo $rest[1]; // you should probably check whether there actually was a match or not

There are multiple ways to do it.

Using strpos and substr:

function rest_of_line($line){
  $loc = strpos($line, '...');
  if($loc !== FALSE){
      return substr($line, $loc+3);
  }
  return $line;
}

$str1 = "hello ... this is the rest of the line";
$str2 = "ASDFDF ... this is also the rest of the line";
echo rest_of_line($str1);
echo rest_of_line($str2);

Or using explode:

$rest = explode('...', $str1, 2); // the 2 ensures that only the first occurrence of ... actually matters.
echo $rest[1]; // you should probably check whether there actually was a match or not
零時差 2024-12-28 10:47:21

...爆炸

它是一个很棒的功能:)

explode it at ...

it's a great function :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文