开发者

regex for size ${word} - php preg_replace

开发者 https://www.devze.com 2023-03-17 16:36 出处:网络
could you help me with the regex for the following examples: lorem ipsum size large lorem ipsum or lorem i开发者_开发技巧psum size m lorem ipsum

could you help me with the regex for the following examples:

lorem ipsum size large lorem ipsum

or

lorem i开发者_开发技巧psum size m lorem ipsum

or

lorem ipsum size 39.5 lorem ipsum 

so in short I am trying to extract one word/string after the word/delimter size until the following white space. so in the above examples it would be (in order): large, m, 39.5.

Any ideas?

Quick update: could you please include also a possibility of

size:$(size)

or

size: $(size)

or

size $(size)


if (preg_match('/\bsize\W+(\S+)/', $subject, $regs)) {
    $result = $regs[1];
} else {
    $result = "";
}

\bsize\W+ matches size plus one or more non-alphanumeric characters (spaces, punctuation etc.), but it doesn't match capsize because of the \b word boundary anchor.

Then (\S+) matches one or more non-whitespace characters and captures them in the first backreference ($regs[1] in this case).


$strings = array(
    'lorem ipsum size large lorem ipsum',
    'lorem ipsum size m lorem ipsum',
    'lorem ipsum size 39.5 lorem ipsum ',
);
foreach ( $strings as $string ) {
    if ( preg_match('#\bsize\b\s+(\S+)\s#', $string, $matches) ) {
        echo "<b>Matched '{$string}':</b>\n\n";
        print_r($matches);
    }
}

Output:

Matched 'lorem ipsum size large lorem ipsum':
Array
(
    [0] => size large 
    [1] => large
)

Matched 'lorem ipsum size m lorem ipsum':
Array
(
    [0] => size m 
    [1] => m
)

Matched 'lorem ipsum size 39.5 lorem ipsum ':
Array
(
    [0] => size 39.5 
    [1] => 39.5
)

Size is stored in $matches[1].


preg_match('/\ssize\s+(\S+)/', $string, $matches);
echo $matches[1];
0

精彩评论

暂无评论...
验证码 换一张
取 消