Get number before selected word form string using preg_match function in php

只愿长相守 提交于 2019-12-06 14:01:18

Regex: ([\d\.]+)(?:mm|\")

([\d\.]+)(?:mm|\") This will match digits , . before mm and ".

PHP code demo

<?php

ini_set('display_errors', 1);
$string='Gold 5.0mm Rolo Chain 18" In';
preg_match_all("/([\d\.]+)(?:mm|\")/", $string,$matches);
print_r($matches);// its 1 index will return your desired result

Or:

Regex: /[\d\.]+(?=mm|\")/

[\d\.]+(?=mm|\") match digits , . and positively look ahead for mm and "

PHP code demo

<?php
ini_set('display_errors', 1);
$string='Gold 5.0mm Rolo Chain 18" In';
preg_match_all("/[\d\.]+(?=mm|\")/", $string,$matches);
print_r($matches);

want to mm number and In number from string.

I guess you can use:

preg_match_all('/[\d.]+/si', $s, $m);
print_r($m[0]);

Output:

Array
(
    [0] => 5.0
    [1] => 18
)
Hamlet
$string = 'Gold 5.0mm Rolo Chain 18" In"';

preg_match('/([\d\.]+)[m]{2}[A-z\ ]+([\d]+)[A-z\"\ ]+/',$string,$matches);

/**
* $match[1] - 5.0
* $match[2] - 18
*/
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!