Jump to content

end of word match


Destramic

Recommended Posts

hey im tring to match words which contain double s at the end...ie. address, business, class etc...so that is so i can put a ' at the end...

class'

			if (preg_match("/ss$/", $name))
			{
				$name = $name . "'";
			}

any help with the regular expression would be great thank you

Link to comment
https://forums.phpfreaks.com/topic/290741-end-of-word-match/
Share on other sites

That code works perfectly fine.

$name = "Address";
if (preg_match("/ss$/", $name))
{
    $name = $name . "'";
}
 
 echo $name; //Output Address'

I'm guessing that the values may not contain what you think they contain. Are there any spaces or other non-printable characters at the end? You may want to trim() them first.

 

But, regular expressions are slow and should be avoided if there are string functions you can use as an alternative. Also, there is no need to use preg_match() function to then add an additional character. You could just use the preg_replace() function. But, I would not do this with RegEx anyway. I would use string functions. Just use substr() to get the last two characters and see if they are both 's'.

$name = "Address";
 
$name = trim($name);
if(strtolower(substr($name, -2))=='ss')
{
    $name .= "'";
}
 
 echo $name; //Output Address'

If that does not work, then do a var_dump() on $name before the function and post the results here.

Link to comment
https://forums.phpfreaks.com/topic/290741-end-of-word-match/#findComment-1489337
Share on other sites

  • 4 weeks later...

Just a note, as this may be your problem. In regexp "$" matches EOL (end of line), that means if you have multiple words you want to match in a single line it will not work. You may instead be looking for "\b" which is a word boundary character. A word boundary is usually triggered by a space or punctuation.

 

I do agree with @Psycho on not using RegExp if it's not necessary. It's simply one of the many tools at our disposal and should be weighed against all other options before being selected as the right tool.

 

However were I to use regex I would process against an entire paragraph, or block of text like this:

preg_replace('/(\w+ss)\b/', '$1\'', $mytext);

 

I hope this was helpful to the op or anyone else who comes across this thread.

 

Link to comment
https://forums.phpfreaks.com/topic/290741-end-of-word-match/#findComment-1492104
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.