Showing posts with label PHP REGEX. Show all posts
Showing posts with label PHP REGEX. Show all posts

Monday, 3 September 2018

PHP Regex how to capture floating-point numbers that do not have a letter at the end

I'm using preg_match_all and I want to capture the floating point numbers that do not have a letter following them.

For example
-20.4a 110b 139 31c 10.4

Desired
[0] => Array
    (
        [0] => 139
        [1] => 10.4
    )

I've tried was able do to the opposite using this pattern:
/\d+(.\d+)?(?=[a-z])/i
which captures the numbers with letters that you can see in this demo. But I can't figure out how to capture the numbers that have no trailing letters.

You can use this regex with a positive lookahead:
[+-]?\b\d*\.?\d+(?=\h|$)

(?=\h|$) asserts presence of a horizontal white space or end of line after matched number.
Alternatively you can use this regex with a possessive quantifier:
[+-]?\b\d*\.?\d++(?![.a-zA-Z])

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)