user875293
user875293

Reputation: 679

how to replace text from a string with an include file in php

I want to know how to replace some text in php string with like an include or something.

here is my example string: I have a string "bla bla bla bla {{ module:projects,id=1 }} bla bla bla bla"

I want to find {{ module:projects,id=1 }} and make it include('projects.php?id=1'); right where it is in the string.

how would i pull this off?

An alternative if i could do this but i cant get it to execute the php from the string would be "bla bla bla bla bla bla"

Upvotes: 0

Views: 2080

Answers (4)

Matteo B.
Matteo B.

Reputation: 4074

  • Are you aware that include('projects.php?id=1'); will include a file named projects.php?id=1 and not projects.php ? To include projects.php and set $_GET['id'] to 1 just do so:

    $_GET['id'] = 1;
    include( 'projects.php' );
    
  • You shoud the take a look at preg_replace. An example (assumed you know what you're doing about the parameters):

    echo preg_replace( '/\\{\\{\\s*module:(\w+)(,(\w+=\w+))?\\s*\\}\\}/',
            'include(\'\\1?\\3\');',
            'bla bla bla bla {{ module:projects,id=1 }} bla bla bla bla' );
    

    Otherwise if my assumption about your parameters and the rest are correct here my solution:

    function replace_modules( $var ){
        $stringparams = array_filter( explode( ',', substr( $var[2], 1 ) ) );
        $getparams = array();
        foreach($stringparams as $stringparam){
            list( $key, $value ) = explode( '=', $stringparam );
            $getparams[] = sprintf('$_GET[\'%s\']=\'%s\';',
                addslashes( $key ),
                addslashes( $value ) );
        }
        return sprintf( '<?php %sinclude(\'%s\') ?>',
            implode( $getparams ), addslashes($var[1]) );
    }
    
    $a= preg_replace_callback( '/\\{\\{\\s*module:(\w+)((,\w+=\w+)*)\\s*\\}\\}/',
        'replace_modules',
        'bla bla bla bla {{ module:projects,id=1,test=hello }} bla bla bla bla' );
    

    EDIT: Okay, now I think I know what you want; here it is:

    function replace_modules( $var ){
        $stringparams = array_filter( explode( ',', substr( $var[2], 1 ) ) );
        foreach( $stringparams as $stringparam ){
            list( $key, $value ) = explode( '=', $stringparam );
            $_GET[$key] = $value;
        }
        ob_start();
        include( $var[1].'.php' );
        return ob_end_clean();
    }
    
    $a= preg_replace_callback( '/{{\\s*module:([^,]+)((,[^,=]+=[^,]*)*)\\s*}}/',
        'replace_modules',
        'bla bla bla bla {{ module:projects,id=1,test=hello }} bla bla bla bla' );
    

Upvotes: 0

Freeman
Freeman

Reputation: 1190

I think you can achieve that using preg_match but to avoid the headache of creating the rule, I'd use explode() to cut out the different parts of the string.

Cut the string in this order:

  1. explode($string, "{{") and fetch the 2nd element in the array ($array[1])

  2. explode($result, "}}") and fetch the 1st element

  3. explode($result, ":") and fetch the 2nd element

  4. explode($result, ",") and fetch both elements

Then you can use

$page = $result[0] . '.php';
$info = $result[1];

Then use include($page.$info);

Upvotes: 0

ChrisBenyamin
ChrisBenyamin

Reputation: 1728

You have to look, if theres a repeating pattern in your string. There are several ways to cut off your string and put it in another shape.

Cleanest approach would be to create a regular expression, then use this e.g. with preg_match

Upvotes: 0

popthestack
popthestack

Reputation: 506

with preg_replace:

$string = '{{ module:projects,id=1 }}';
$string = preg_replace('/{{ module:([^,]+),id=([0-9]+) }}/', 'include(\'$1.php?id=$2\')', $string);
// $string == include('projects.php?id=1')

Note: you can't actually include files with query strings on the end. PHP looks for file named 'projects.php?id=1'.

To get the file and actually include it:

preg_match_all('/{{ module:([^,]+),id=([0-9]+) }}/', $string, $matches);
foreach ($matches[1] as $key => $filename) {
    // set $id before including the file. you could optionally set $_GET['id'].
    $id = $matches[2][$key];
    include($filename . '.php');
}

To support multiple parameters. Similar to Matmarbon's, but is more compact, doesn't assume parameter values will conform to \w, doesn't escape values, but also has less room for variations in spacing (/s*).

preg_match_all('/{{ module:([^,]+)((,[^=]+=[^,}]+)*) }}/', $string, $matches);
foreach ($matches[1] as $key => $filename) {
    foreach (explode(',', trim($matches[2][$key], ', ')) as $vars) {
        list($k, $v) = explode('=', $vars);
        $_GET[$k] = $v;
    }
    // then this:
    include($filename . '.php');
    // or, to replace content:
    ob_start();
    include($filename . '.php');
    $contents = ob_get_contents();
    ob_end_clean();
    $string = str_replace($matches[0][$key], $contents, $string);
}

Upvotes: 3

Related Questions