James Juanjie
James Juanjie

Reputation: 219

How to only find a substring in a string?

I have a large strings on my php page.

I need to find a small part of this large string.

For example the large string looks like this:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen _ Document Number : 4575 - NIA - 000 book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release Date: 2016 - 03 - 04 of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

So, what I need to find and display in my php page is the Document Number : 4575 - NIA - 000 and the Date: 2016 - 03 - 04.

I tried something like this:

$date = substr($result, 0, strpos($result, 'Date:'));
echo $date;

But this doesn't produce the required output on my php page.

How do I solve this problem?

Upvotes: 0

Views: 52

Answers (1)

Andreas
Andreas

Reputation: 23958

You can use regex.

This pattern will find what you need.
Since it's a very long regex I'm not going to explain it in detail, but you can easily find information about how regex work.

preg_match_all("/Document\s+Number\s*:\s*(.*?\s*-.*?\s*-\s*.*?)\s|Date\s*:\s*(\d{4}\s*-\s*\d{2}\s*-\s*\d{2})/i", $str, $matches);

But in short, it will look for patterns and capture the needed part of the string.
\s* or \s+ is space, either optional (*) or a requirement but unlimited allowed (+).
\d is digit. \d+ will be any length of digits. \d{4} is four digits.
.* is any length of anything.

https://3v4l.org/nY1aM

Upvotes: 1

Related Questions