I
I
Ilya Parshakov2018-03-16 00:48:34
PHP
Ilya Parshakov, 2018-03-16 00:48:34

How to extract numbers and a dot from a string, between certain characters?

Hello! Please tell me, I've already broken my whole head, it doesn't work.
Let's say there is a line:
width: 287.942px; height: 162px;
How, for example, to extract only the first number ( 287.942 )? And how to extract only the second number ( 162 )?
So far, it was possible to extract only all the numbers with a dot:

preg_replace('/[^\d.]/', '', 'width: 287.942px; height: 162px;');

ps I promise to read the book on regular expressions and henceforth do not ask such questions again :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick Sdk, 2018-03-16
@parschakov

preg_match('#width:\s*(\d+(?:\.\d+)?)px.*?height:\s*(\d+(?:\.\d+)?)px#is', $str, $match)

we get an array $match with content like:
$match = [
  '0' => 'width: 287.942px; height: 162px;',
  '1' => '287.942',
  '2' => '162',
];

individually:
preg_match('#height:\s*(\d+(?:\.\d+)?)px#is', $str, $match)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question