preg_match must end with "/"?
In the preg_match below, I'm comparing against two static strings, $url and $my_folder...
$url = get_bloginfo('url')
//$url = 'http://site.com'
$my_folder = get_option('my_folder');
//$my_folder = 'http://site.com/somefolder;
I'm getting a match when the $my_folder string has a trailing slash
http://somefolder/go/
But this does not create a match...
http://somefolder/go
However, another problem is that this also matches...
http://somefolder/gone
Code is...
$my_folder = get_option('rseo_nofollow_folder');
if($my_folder !=='') $my_folder = trim($my_folder,'/');
$url = trim(get_bloginfo('url'),'/');
preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
for ( $i = 0; $i <= sizeof($matches[0]); $i++){
if($my_folder !=='')
{
//HERES WHERE IM HAVING PROBLEMS
if ( !preg_match( '~nofollow~is',$matches[0][$i])
&& (preg_match('~' . $my_folder . '/?$~', $matches[0][$i])
|| !preg_match( '~'. $url .'/?$~',$matches[0][$i])))
{
$result = trim($matches[0][$i],">");
$result .= ' rel="nofollow">';
$content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
}
}
else
{
//THIS WORKS FINE, NO PROBLEMS HERE
if ( !preg_match( '~nofollow~is',$matches[0][$i]) && (!preg_match( '~'.$url.'~',$matches[0][$i])))
{
开发者_开发知识库$result = trim($matches[0][$i],">");
$result .= ' rel="nofollow">';
$content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
}
}
}
return $content;
~^http://somefolder/go(?:/|$)~
You need to first remove the trailing slash and add '/?' at the end of your regexp
$my_folder = trim($my_folder,'/');
$url = trim(get_bloginfo('url'),'/');
if ( !preg_match( '~nofollow~is',$matches[0][$i])
&& (preg_match('~' . $my_folder . '/?$~', $matches[0][$i])
|| !preg_match( '~'. $url .'/?$~',$matches[0][$i])))
This is a shot in the dark, but try:
preg_match( '/' . preg_quote( get_bloginfo('url'), '/' ) . '?/', $matches[0][$i] )
You can use whatever char you want in place of the /
chars. I'm guessing that you're using wordpress and guessing that get_bloginfo('url')
is normalized to always have a trailing slash. If that is the case, the last slash will be selected optionally by the ?
at the end of the regex.
You should just use strstr()
or strpos()
if it's fixed strings anyway.
Your example rewritten:
if (!strstr($matches[0][$i], "nofollow")
and strstr($matches[0][$i], $my_folder)
or !strstr($matches[0][$i], $url) )
strpos works similarly, but you need an extra boolean check:
if (strpos($matches, "nofollow") === FALSE
or strpos($matches, $my_folder) !== FALSE)
精彩评论