Jump to content

[SOLVED] A bit of regexp help


liamthebof

Recommended Posts

OK, I am after a bit of regexp help I believe.

 

What I have is:

 

A external file looking like below:

Information - Name: Cat - Details: The cat ran up the mat

Information - Name: Dog - Details: The dog chased the cat

Information - Name: Fish - Details: The fish was scared of the cat

Information - Name: Plant - Details: The sun beamed on the plant

 

New information is constantly added to this file at the bottom

So far, I have done a count, done a file() based on the count and got the complete string : Information - Name: Plant - Details: The sun beamed on the plant

from the bottom which is what I was after.

 

Now, I need to harvest the 'Fish' as string $name and the 'The sun beamed on the plant' as string $details.

 

HOWEVER, if the details string if longer than 20 characters, as the plants details are, I need the first 20 characters saved $details1 and the seconds 20 as $details2.

 

All help is appreciated. Thank you very much for answering.

 

Link to comment
https://forums.phpfreaks.com/topic/118538-solved-a-bit-of-regexp-help/
Share on other sites

No need to use slow regex.

 

<?php

$line = 'Information - Name: Plant - Details: The sun beamed on the plant';

# Break string into pieces
$pcs = explode( ' - ', $line );

# Remove first 6 chars (Name: ) from name
$name = substr( $pcs[1], 6 );
# Remove first 9 chars (Details: ) from details
$details = substr( $pcs[2], 9 );

# Check if details has more than 20 chars
if ( strlen($details) > 20 ) {
  # Split into groups of 20 characters
  $arr = str_split( $details, 20 );
  # Covert to requested format
  $i = 1;
  foreach ( $arr as $chunk ) {
    $var_name = 'details' . $i;
    $$var_name = $chunk;
    $i++;
  }
}

echo $name . '<br>';
echo $details1 . '<br>';
echo $details2 . '<br>';

?>

 

Though I don't really see a need to change the values from an array to $details1, $details2 ect..

Thanks, worked a charm.

 

Also, it is because there values are being wrote to an image as the less then 20 characters is an image width constraint.

 

Thanks for the help.

 

I was more referring to why you'd populate $details1, $details2, ect... when you could use

 

# Remove first 9 chars (Details: ) from details
$details = array( substr( $pcs[2], 9 ) );

# Check if details has more than 20 chars
if ( strlen($details[0]) > 20 ) {
  # Split into groups of 20 characters
  $details = str_split( $details[0], 20 );
}

# You can now loop through all your values with ease
foreach( $details as $detail )
  echo $detail . '<br>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.