Jump to content

how to get the matching keyword??


gudfry

Recommended Posts

How would I write some php code that opens up a text file, looks for a specific line, and output it?

Basically I have a text file called test.txt, which has a list of all the general comment(/* $Author : Chad */) stored, one line at a time. And if I want to echo only the (Author : Chad) insted of(/* $Author : Chad */), I basially have to dispaly it on the screen.

pls help me

Link to comment
https://forums.phpfreaks.com/topic/115988-how-to-get-the-matching-keyword/
Share on other sites

hello all;

 

          Im doing this way but it doesnt work.

 

          function processLine($line) {

 

if(strpos($line,'/* $')===0) {

// chexk for the ':'

if(strpos($line,':')>=5) {

// check for the ending '*/'

if (strpos($line,'*/')>=6) { // we have a matching string, so get the values and returnin  array

 

$retval=Array();

 

$positionOfColon=strpos($line,":");

//echo $positionOfColon;

$lengthOfString0Ineed=$positionOfColon-4; // or something like that, might miss 1

 

$retval[0]=substr($line,4,$lengthOfString0Ineed);

$retval[1]=substr($line,$positionOfColon+1,strlen($line)-$positionOfColon-3);

 

return $retval;

}

else { // third condition not met

return false;

 

}

}

else { // no match for '/* $' at the beginning of the line

return false;

}

 

$lines = file('test.php');

    foreach ($lines as $linenum => $line) {

    echo "Lines #<b>{$linenum}</b> : " . htmlspecialchars($line) . "<br/>\n";

}

$input='echo "Lines #<b>{$linenum}</b> : " . htmlspecialchars($line) . "<br/>\n";';

 

$output=processLine($input);

if (gettype($output)=="array")

echo '<p>Title: '.($output[0]).' Value: '.$output[1].'</p>';

else

echo '<p>Not a string according to definition</p>';

 

heres a quick version, may be easier (untested)

<?php
$file = "test.txt";
$regex = '%\(/\* \$(.*?) : (.*?) \*/\)%si';

$lines = file($file);
foreach ($lines as $line_num => $line)
{
if (preg_match($regex, $line))
{
$result = preg_replace($regex, '(\1 : \2)', $line);
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($result) . "<br />\n";
}
}
?>

 

Another Version (without line numbers)

<?php
$file = "test.txt";
$regex = '%\(/\* \$(.*?) : (.*?) \*/\)%si';
$lines = file_get_contents($file);
echo preg_replace($regex, '(\1 : \2)', $lines);
?>

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.