Skip to content

Instantly share code, notes, and snippets.

@egyjs
Last active November 14, 2019 03:47
Show Gist options
  • Save egyjs/fd510b9da7cc5cf398bea79356d00e48 to your computer and use it in GitHub Desktop.
Save egyjs/fd510b9da7cc5cf398bea79356d00e48 to your computer and use it in GitHub Desktop.
make 'string syntax' to dynamic Laravel php
function ElzahabyDynamicLaravelString($model,$syntax,$sign=null){
if (isset($model) && $syntax == null){
$input = $model::getListFields()['syntax'];
}else {
$input = $syntax;
}
$output = $input;
$regex = '/'.(($sign != null)?$sign:':-:').'[a-z._]+/im';
if (preg_match_all($regex, $input, $matches, PREG_PATTERN_ORDER)) {
foreach ($matches[0] as $word) {
$call = $model;
$ModelWithCol = str_replace(':-:','',$word);
$myCols = explode('.', $ModelWithCol);#unset($myCols[0]);
foreach ($myCols as $col):
if (isset($call->$col)) {
$call = $call->$col;
}
endforeach;
$replaceWith = $call;
$output = str_replace($word,$replaceWith,$output);
}
return ($output);
}
return $output;
}
/*
Made by [egy.js](https://www.instagram.com/egy.js/);
*/

exmaple

$item = User::find(1);
$syntax = 'hi :-:name, i loved your photo: <img src=":-:img">,its really Laravel! ..';
dd(ElzahabyDynamicLaravelString($item));

// this will return:
'hi A. El-zahaby, i loved your photo: <img src="src-of-image-on-the-database.png">,its really Laravel! .. '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment