如何执行 preg_replace() 来删除除“Post”之外的任何内容还是“帖子”?

发布于 2024-11-08 22:23:08 字数 79 浏览 1 评论 0原文

我有一个字符串,它返回各种内容,如数字、空格等。我想要的只是“Post”或“Posts”。有人可以给我一个如何在 PHP 中执行此操作的示例吗?

I have a string that returns various stuff like numbers, spaces, etc. All I want from it is just "Post" or "Posts". Can someone give me an example of how to do this in PHP?

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

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

发布评论

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

评论(4

背叛残局 2024-11-15 22:23:08

是的,像这样使用 preg_match

$myData = "There are 15 posts in this forum.";
preg_match("/Posts?/", $myData, $results);
if($results[0][0] === "Posts") {
     // It was "posts"
} else {
     // Assume it was "post"
}

Yup, use preg_match like so:

$myData = "There are 15 posts in this forum.";
preg_match("/Posts?/", $myData, $results);
if($results[0][0] === "Posts") {
     // It was "posts"
} else {
     // Assume it was "post"
}
清眉祭 2024-11-15 22:23:08
$post = preg_replace('/.*(Posts?).*/', '$1', $string);

如果您只想检测单词 Post 是否在字符串中,那么使用 strpos() 会更有效。

if (strpos($string, 'Post') !== FALSE) {
   ... Post  is present ...
}
$post = preg_replace('/.*(Posts?).*/', '$1', $string);

If you just want to detect if the word Post is in the string, then using strpos() would be far more efficient.

if (strpos($string, 'Post') !== FALSE) {
   ... Post  is present ...
}
神妖 2024-11-15 22:23:08

如果您正在测试字符串是否包含单词“Posts”,那么您可以使用如下内容:

if (preg_match("/Posts/i", $theString)) {
  // do something
}

if you are testing to see if the string contains the word "Posts" then you could use something like this:

if (preg_match("/Posts/i", $theString)) {
  // do something
}
清眉祭 2024-11-15 22:23:08

如果我没看错的话,似乎您不需要字符串 Post/Posts,只要它们存在即可。如果是这种情况,最快的方法是使用 strpos函数。您可以按如下方式使用它:

if( strpos($haystack,"Post") !== false ) {
    //You get here if Post or Posts was found.
}

If I'm reading that correctly, it seems that you don't need the string Post/Posts, just if they exist. If that is the case the fastest way would be to use the strpos function. You could use it as follows:

if( strpos($haystack,"Post") !== false ) {
    //You get here if Post or Posts was found.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文