简体   繁体   中英

How can I grab the only part of a string that matches a regular expression?

例如,如果我的HTML输入为123Smith456%$@#***()NotSmith ,而我只想要字母字符,那么如何使用正则表达式来匹配并抓住Smith并将其放入变量中?

You can do this by using the PREG_OFFSET_CAPTURE option in the preg_match function.

Your expression needs to be wrapped in () to group the matches you wish to capture. You can have any number of groups, so you can capture various parts and store them in various variables.

For example:

$string = '123Smith456%$@#***()NotSmith';

preg_match('/(Smith)/', $string, $matches, PREG_OFFSET_CAPTURE);

print_r($matches);

This will output:

Array
(
    [0] => Array
        (
            [0] => Smith
            [1] => 3
        )

    [1] => Array
        (
            [0] => Smith
            [1] => 3
        )

)

If you are looking to extract all the actual "words" you could do something like this:

$string = '123Smith456%$@#***()NotSmith';

preg_match('/([A-Za-z]+)/', $string, $matches, PREG_OFFSET_CAPTURE);

print_r($matches);

This will match all occurrences of anything has characters in the range of AZ or az which occur once or more. Which outputs:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Smith
                    [1] => 3
                )

            [1] => Array
                (
                    [0] => NotSmith
                    [1] => 20
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Smith
                    [1] => 3
                )

            [1] => Array
                (
                    [0] => NotSmith
                    [1] => 20
                )

        )

)

See: https://secure.php.net/manual/en/function.preg-match.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM