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

泪湿孤枕 提交于 2019-12-07 22:25:56

问题


I am trying to get the mm and inches values from the following string using preg_match.

$string = "Gold 5.0mm Rolo Chain 18" In";

How can I do this?


回答1:


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);



回答2:


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
)



回答3:


$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
*/


来源:https://stackoverflow.com/questions/43516500/get-number-before-selected-word-form-string-using-preg-match-function-in-php

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