GivenPie
GivenPie

Reputation: 1489

How do I extract text from a line using substr?

I would like to extract 2 pieces information from a text file using the substr method in PHP. Some sample lines are as follows

 CON8101 Residential Building/Estimating 6 hrs/w 
 CON8411 Construction Materials I 4 hrs/w
 CON8430 Computers and You 4 hrs/w

I need to extract the number of hours each course requires. Is the function I wrote correct to extract the number from the back of the line? I have come up with the function:

            function GetCourseHours($couseList)
    {//using 7 character placements from the end, taking 1 value (number)
        $courseHours = substr(courseList, -7, 1);
    }

And next, to extract everything except for the number of hrs/w, like CON8101 Residential Building/Estimating. I'm not sure how to express in substr to extract everything but the last 7 character spaces from the line. To get course name and ID only.

            function GetCourseName($courseList)
    {//how do I only emit the last 7 placements of the txt string?
        $courseName = substr(courseList, ..., ...)
    }

Upvotes: 0

Views: 176

Answers (2)

Subash
Subash

Reputation: 3168

first is correct, for 2nd use this $courseName = substr($courseList, 0, strlen($courseList)-7); see here http://us.php.net/manual/en/function.substr.php

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120644

The PHP documentation on substr covers all of the information you need to know about its behavior:

function GetCourseName($courseList)
{
    $courseName = substr($courseList, 0, -7);
}

The relevant portion of that documentation for your application is:

If length (the 3rd argument) is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative).

Upvotes: 1

Related Questions