Monday 3 September 2018

PHP regex to test punctuation in a string that does not have at least one space immediately before or after

I need help detecting when a string contains punctuation that does not have a space before or after it, or end of line.

It is difficult for me to explain in words, so I will try by example:
This should pass test:
hello, my friend
hello ,my friend
hello , my friend
hello my friend
hello my friend.

This would fail test:
hello,my friend
hello, my friend,have a nice day

The function I am hoping is simple like this:
function punctest($str)
{
    if (preg_match("[:punct:]",$str))
    {
        if (SOME_REGEX_GOES_HERE)
        {
            $okay = 1; // punctuation found, but has a space before OR after it
        }
        else
        {
            $okay = 0; // punctuation found, not no space found either side
        }

    }
    else
    {
        $okay = 1; // no punct found
    }
}


To elaborate on @Riaz's answer, you just want to reject string that matches /\S[[:punct:]]\S/:
<?php                                                                                                                                       

function punctest($str)
{
    return !preg_match('/\S[[:punct:]]\S/', $str);
}

var_dump(punctest('hello, my friend'));
var_dump(punctest('hello,my friend'));

prints
bool(true)
bool(false)

0 comments:

Post a Comment