Jenz Jenz - 2 months ago 5
PHP Question

Extract dimensions from a string using PHP

I want to extract the dimension from this given string.

$str = "enough for hitting practice. The dimension is 20'X10' *where";

I expect 20'X10' as the result.

I tried with the following code to get the number before and after the string 'X. But it is returning an empty array.

$regexForMinimumPattern ='/((?:\w+\W*){0,1})\'X\b((?:\W*\w+){0,1})/i';
preg_match_all ($regexForMinimumPattern, $str, $minimumPatternMatches);

Can anyone please help me to fix this? Thanks in advance.


Just remove the \b from your pattern (and append a \' in the end if you want the trailing quote):

$regexForMinimumPattern ='/((?:\w+\W*){0,1})\'X((?:\W*\w+){0,1})\'/i';

NB: \b is the meta-character for word-boundaries, you don't need it here.