Kelso
Kelso

Reputation: 387

trying to replace/edit line AFTER search string in php

for example, I have a file like this

MistaFuzzy:
    group: VIP
    permissions: null
Spooner425:
    group: VIP
    permissions: null

I need to be able to search on the name, and manipulate the line under, for the time being, just changing VIP to VIP2.

Im thinking i need to use substr_replace but am a loss as to how to accomplish this.

Upvotes: 1

Views: 265

Answers (3)

Galen
Galen

Reputation: 30170

I recommend learning regular expressions

Heres a function that will allow you to change any value if a file is formatted like that

$str = <<<END

MistaFuzzy:
    group: VIP
    permissions: null
Spooner425:
    group: VIP
    permissions: null

END;

function updateFile( $username, $key, $value, $str ) {
    return preg_replace(
        sprintf( "~%s:(.*?)%s:.*?\n~sm", $username, $key ),
        sprintf( "%s:$1%s: %s\n", $username, $key, $value ),
        $str
    );
}

echo updateFile( 'Spooner425', 'permissions', '3', $str );

Read this webpage everyday until you understand them! http://www.regular-expressions.info/

Upvotes: 2

Alix Axel
Alix Axel

Reputation: 154553

You can use a regular expression:

$user = preg_quote('Spooner425', '~');
$new_group = addcslashes('VIP2', '\\$');
$string_input = file_get_contents('/path/to/your/file.txt');
$string_output = preg_replace('~(.+)(' . $user . ':\s+group:\s+)[^\s]+(.+)~s', '$1$2' . $new_group . '$3', $string);

echo '<pre>';
print_r($string_output);
echo '</pre>';

The above should output this:

MistaFuzzy:
    group: VIP
    permissions: null
Spooner425:
    group: VIP2
    permissions: null

Upvotes: 0

julio.aescobar
julio.aescobar

Reputation: 61

why not use a xml file?

<?xml version="1.0" encoding="iso-8859-1"?>

<names>
**<name username="MistaFuzzy">**
 <group>VIP</group>
 <permissions>null</permissions>
**</name>**
**<name username="Spooner425">**
 <group>VIP</group>
 <permissions></permissions>
**</name>**
</names>

and then you can use SimpleXML (PHP5). See this http://onlamp.com/pub/a/php/2004/01/15/simplexml.html

Upvotes: 1

Related Questions