Viewed   60 times

I have strings:

$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three =  'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';

How can I find the numeric digits in these strings?

Maybe with function:

function numbers($string){

    // ???

    $first = ?;
    $second = ?;
}

For example:

function numbers($one){

    // ???

    $first = 4;
    $second = 5;
}

function numbers($two){

    // ???

    $first = 2;
    $second = NULL;
}

Best way for this maybe is regex, but how can I use this for my example? Maybe without regex?

 Answers

4

You can use regular expressions for this. The d escape sequence will match all digits in the subject string.

For example:

<?php

function get_numerics ($str) {
    preg_match_all('/d+/', $str, $matches);
    return $matches[0];
}

$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';

print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));

https://3v4l.org/DiDBL

Sunday, October 2, 2022
5

This shouldn't be too hard.

$str = '<div id="post_message_957119941">';

if ( preg_match ( '/post_message_([0-9]+)/', $str, $matches ) )
{
    print_r($matches);
}

Output:

Array ( [0] => post_message_957119941 [1] => 957119941 )

So the desired result will always be in: $matches[1]

Is that what you need?

Thursday, December 1, 2022
 
5

The Arabic regex is:

[u0600-u06FF]

Actually, ?-? is a subset of this Arabic range, so I think you can remove them from the pattern.

So, in JS it will be

/^[a-z0-9+,()/'su0600-u06FF-]+$/i

See regex demo

Tuesday, October 11, 2022
3

If it is always in that format then this should work without using a regular expression:

$color = str_replace(array('rgb(', ')', ' '), '', $color);
$arr = explode(',', $color);

We use str_replace() to strip out the uninteresting data and whitespace and then explode() the string on commas to give the output array format you desire in $arr.

I have also added this solution to a codepad so you can see what happens when you run it.

Friday, December 23, 2022
 
3

For this PHP regex:

$str = preg_replace ( '{(.)1+}', '$1', $str );
$str = preg_replace ( '{[ '-_()]}', '', $str )

In Java:

str = str.replaceAll("(.)\1+", "$1");
str = str.replaceAll("[ '-_\(\)]", "");

I suggest you to provide your input and expected output then you will get better answers on how it can be done in PHP and/or Java.

Sunday, October 9, 2022
 
haodong
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :