I have a string that returns vari开发者_C百科ous 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?
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"
}
$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 ...
}
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
}
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.
}
精彩评论