Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.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 如何执行preg_replace()以删除除“以外的任何内容”;邮政「;或;职位;?_Php_Preg Replace - Fatal编程技术网

Php 如何执行preg_replace()以删除除“以外的任何内容”;邮政「;或;职位;?

Php 如何执行preg_replace()以删除除“以外的任何内容”;邮政「;或;职位;?,php,preg-replace,Php,Preg Replace,我有一个字符串,它返回各种东西,如数字、空格等。我只想从中得到“Post”或“Posts”。有人能给我一个如何在PHP中实现这一点的例子吗 $post = preg_replace('/.*(Posts?).*/', '$1', $string); 如果您只想检测字符串中是否有单词Post,那么使用strpos()将更有效率 if (strpos($string, 'Post') !== FALSE) { ... Post is present ... } 如果您正在测试字符串是否包

我有一个字符串,它返回各种东西,如数字、空格等。我只想从中得到“Post”或“Posts”。有人能给我一个如何在PHP中实现这一点的例子吗

$post = preg_replace('/.*(Posts?).*/', '$1', $string);
如果您只想检测字符串中是否有单词
Post
,那么使用
strpos()
将更有效率

if (strpos($string, 'Post') !== FALSE) {
   ... Post  is present ...
}

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

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

是的,像这样使用
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"
}

如果我读对了,那么您似乎不需要字符串Post/Posts,只要它们存在。如果是这种情况,最快的方法就是使用函数。您可以按如下方式使用它:

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

如果只使用
stripos
而不是
preg\u replace
搜索“Post”或“Posts”的存在,这可能更容易实现。