הוסטס - פורום אחסון האתרים הגדול בישראל

הוסטס - פורום אחסון האתרים הגדול בישראל (https://hosts.co.il/forums/index.php)
-   פורום תיכנות (https://hosts.co.il/forums/forumdisplay.php?f=14)
-   -   PHP | משהו מתפקשש עם preg_replace (עזרה) (https://hosts.co.il/forums/showthread.php?t=105948)

Penetration 17-12-13 21:14

PHP | משהו מתפקשש עם preg_replace (עזרה)
 
PHP קוד:

$text "replace -> {var} <- was var...";
$temp["var"] = "!!!this is var!!!";
echo 
preg_replace('/\{(.*)\}/'"$temp[$1]"$text); 

הרעיון הוא להחליף בטקסט מסוים את {var} באיבר שהאינדקס שלו הוא var במערך מסוים...
בארגומנט replace של preg_replace ניסיתי גם לשים את האופציות הבאות:
PHP קוד:

$temp[$1]
$temp["$1"]
"$temp[\1]" 

ועוד...

תודה לעוזרים :)

MAORBARI 18-12-13 00:03

PHP קוד:

echo preg_replace('/\{(\w*?)\}/i'$temp['$1'], $text); 


אדיר 18-12-13 00:18

http://krasimirtsonev.com/blog/artic...n-just-20-line

MAORBARI 18-12-13 02:47

טעיתי.. תיקון קוד:
PHP קוד:

preg_replace('/\{(.*?)\}/ei''print str_replace(\'{$1}\', $temp[\'$1\'], $text);'$text); 

יש גם את האפשרות הזו:
PHP קוד:

echo preg_replace_callback('/\{(.*?)\}/i', function($varMatches) {
    return 
$GLOBALS['temp'][$varMatches[1]];
}, 
$text); 


Penetration 18-12-13 10:41

ציטוט:

נכתב במקור על ידי MAORBARI (פרסם 885035)
טעיתי.. תיקון קוד:
PHP קוד:

preg_replace('/\{(.*?)\}/ei''print str_replace(\'{$1}\', $temp[\'$1\'], $text);'$text); 

יש גם את האפשרות הזו:
PHP קוד:

echo preg_replace_callback('/\{(.*?)\}/i', function($varMatches) {
    return 
$GLOBALS['temp'][$varMatches[1]];
}, 
$text); 


האמת שלאפוציה הראשונה כבר הגעתי, כמובן שעובדת מצוין אבל בעייתית מאוד כי מעורב בה eval...
מנסה להימנע מזה...
לגבי האופציה השניה - לא רצה...

Haimz 18-12-13 14:46

PHP קוד:

<?php
    $text 
"My name is: {name} and i love play {game} and i work at {company_name}";
    
$data['name'] = "Haim";
    
$data['game'] = "Basketball";
    
$data['company_name'] = "Haimz.net";

    
$text preg_replace_callback("/\{([a-zA-Z0-9_]+?)\}/""replaceVars"$text);

    function 
replaceVars($match)
    {
        global 
$data;
        return 
$data[$match[1]];
    }

    echo 
$text;
?>


Penetration 19-12-13 00:11

ציטוט:

נכתב במקור על ידי Haimz (פרסם 885042)
PHP קוד:

<?php
    $text 
"My name is: {name} and i love play {game} and i work at {company_name}";
    
$data['name'] = "Haim";
    
$data['game'] = "Basketball";
    
$data['company_name'] = "Haimz.net";

    
$text preg_replace_callback("/\{([a-zA-Z0-9_]+?)\}/""replaceVars"$text);

    function 
replaceVars($match)
    {
        global 
$data;
        return 
$data[$match[1]];
    }

    echo 
$text;
?>


מצוין עובד תודה :)


כל הזמנים הם GMT +2. הזמן כעת הוא 10:17.

מופעל באמצעות VBulletin גרסה 3.8.6
כל הזכויות שמורות ©
כל הזכויות שמורות לסולל יבוא ורשתות (1997) בע"מ