substring - PHP - How to check if the first 4 values of a string on a line are numerical

105

sorry if this is a simple question, I just moved into web dev from being a Jr. Systems Admin so I'm still pretty new.

As my first project, I am building a php web app that will upload an accounting file(plain text), parse it line by line, strip the excess stuff, and then display it.

I already have the uploading and displaying part completed (using fopen and fgets to return it line by line).

Now what I would like to know is how I can get php to only echo the lines that start with 4 numbers (the reason for this is that there are titles and headers on every new page, its a multi page document, and the account numbers range from either 4 numbers to 8 numbers).

Would I use substr() or mb_substr() to specify a check of the first 4 characters of every new line that fgets() puts out, and then use is_numeric() to check if they are numbers?

PS: Sorry if my terminology is slightly off. I have a degree in finance and have been self-teaching myself coding, completely different world lol.

76

Answer

Solution:

I believe you mean 4 first characters are digits. You might wanna use regular expressions for that:

if (preg_match('/^\d{4}.*/', $yourSingleLineString))
{
    //it is starting by 4 digits so do what you need to
}

preg_match checks if your string matches the pattern given. The pattern actually says: starting from the beginning of the line (^) the digit (\d) repeats 4 times ({4}) and then there are any characters (.) zero or more times (*).

People are also looking for solutions to the problem: javascript - I want to create advanced search using ajax codeigniter per categories

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.