I'm trying to parse some input using regex. The input will be in the format:
{somevalue:3}
The aim is to display 'som' (no quotemarks).
At the moment, I have:
'echo' => array(
'search' => '~\{((?:'.$this->preg['var'].')(?:\.)?)\}~sU',
'replace' => "'.\$this->_get('\\1').'"
)
Which works great with my template system, to echo the standard variable (i.e. 'somevalue'). However, I wish to allow the user to use the : delimiter to limit the number of characters to output (i.e. {somevalue:3} would display 'som').
I tried:
'echo' => array(
'search' => '~\{((?:'.$this->preg['var'].')(?:\.)?:(.*)/)\}~sU',
'replace' => "'.substr(\$this->_get('\\1'),0,\\2).'"
)
But this didn't work. I don't really understand regex to be honest so any help would be much appreciated.
It looks like you have an extra '/' in the new search expression.
|
v
'search' => '~\{((?:'.$this->preg['var'].')(?:\.)?:(.*)/)\}~sU',
I'm not familiar with the templating system you're using, but it appears that the replace expression would need to be changed as well.
'replace' => "'.substr(\$this->_get('\\1'),0,\$this->_get('\\2')).'"
Put these together and you'd get something like this to try:
'echo' => array(
'search' => '~\{((?:'.$this->preg['var'].')(?:\.)?:(.*))\}~sU',
'replace' => "'.substr(\$this->_get('\\1'),0,\$this->_get('\\2')).'"
)
It should be noted that if this works, the old way of doing input won't work anymore. In other words, you'll always have to use the format {<string>:<num_of_chars>} and not just {<string>}.
$s = preg_replace_callback(
'/\{([^:]+):(\d+)\}/',
create_function('$m', 'return substr($m[1], 0, $m[2]);'), $s);
Test this code here.
Related
I have an associate array inside a PHP class method going like this:
// ...
$filters = [
self::FILTER_CREATION_DATE => "Base/*/Creation/Date.php",
self::FILTER_CREATION_DATE_BETWEEN => "Base/*/Creation/Date.php",
self::FILTER_CREATION_DATE_GREATER => "Base/*/Creation/Date.php",
self::FILTER_CREATION_DATE_GREATER_OR_EQUAL => "Base/*/Creation/Date.php",
self::FILTER_CREATION_DATE_LESS => "Base/*/Creation/Date.php",
self::FILTER_CREATION_DATE_LESS_OR_EQUAL => "Base/*/Creation/Date.php",
];
// ...
What I would like to do is to convert this string from:
self::FILTER_CREATION_DATE_BETWEEN => "Base/*/Creation/Date.php",
to this one:
self::FILTER_CREATION_DATE_BETWEEN => "Base/*/Creation/Date/Between.php",
I would like to use a RegEx to extend the string but leave the rest untouched. I need to do this because there's more than 120 constants defined ending with *_BETWEEN.
How can I do this?
In the Intellij editor or the free Notepad++, you can find and replace by regex.
I'm sure other IDE's have similar functionality
Find self::([_A-Z]+)_BETWEEN => "(.*)/Date.php"(,)*
Replace self::$1_BETWEEN => "$2/Date/Between.php"$3
The regex groups the variable components of your search together by wrapping it in ()
In the replace you can reference them in order by $1, $2, etc..
I have a variable which needed a value from a specific query
$player_id_owner = $this->Player->fetchAll('Select id from player
where name = ?', array($name));
$player_id_owner = ($this->Player->find('all', array(
'fields' => array('id'),
'conditions' => array('Player.name' => '$name')
)));
i tried both raw query and cakephp find but both of them returns only "array"
have i forgotten something? how can i access the expected result from query? thanks
Well
'Player.name' => '$name'
is not valid PHP code, at least not for what you try to do.
Don't escape variables as strings:
'Player.name' => $name
You could have easily seen that by checking the resulting query in the debug kit or the bottom of the view.
And most likely you would want to use find('first', ...) as documented if you only expect a single entry here.
Last but not least:
You most likely just lack basic debugging skills. Don't echo it, as it is indeed an array. Never do that with unknown variables as they often are everything but a basic string.
Use debug() to see whats inside and then properly echo what you see, e.g. echo $player['Player']['name'];.
Bear in mind that stringish output should be secured by h() on output:
echo h($player['Player']['name']);
try this
$player_id_owner = $this->Player->find('first', array(
'fields' => array('id'),
'conditions' => array('Player.name' => $name)
));
or try (you can also use your variable instead of yourname)
'conditions' => array('Player.name LIKE' => "%yourname%")
after that you can get the id with
$player_id_owner['Player']['id']
I'm working on a drupal site and when debugging, I am always having to read through long, nested arrays. As a result, a large portion of my life is spent using the arrow, return, and tab keys, to split up 1000+ character strings into a nested, readable format.
For drupal devs, I can't use devel's dsm(), as I'm working with multi-step #ahah/#ajax forms, and I can only output the arrays to the error log, not to the screen.
Visual example:
Evil:
array ( 'form_wrapper' => array ( '#tree' => true, '#type' => 'fieldset', '#prefix' => '', '#suffix' => '', '#value' => '', 'name' => array ( '#type' => 'textfield', '#title' => NULL, '#size' => 60, '#maxlength' => 60, '#required' => false, '#description' => NULL, '#attributes' => array ( 'placeholder' => 'Email', ), '#post' => array ( 'form_wrapper' => array ( 'name' => '', 'pass' => '', ), ...
Good:
array (
'form_wrapper' => array (
'#tree' => true,
'#type' => 'fieldset',
'#prefix' => '<div>',
'#suffix' => '</div>',
'#value' => '',
'name' => array (
'#type' => 'textfield',
'#title' => NULL,
'#size' => 60,
'#maxlength' => 60,
'#required' => false,
'#description' => NULL,
'#attributes' => array (
'placeholder' => 'Email',
),
Edit: Sorry, by "not output to screen", I meant via drupal's system messages where it's possible to output arrays in a clickable, nested format (using devel.module).
If you need to log an error to Apache error log you can try this:
error_log( print_r($multidimensionalarray, TRUE) );
http://php.net/manual/en/function.print-r.php
This function can be used to format output,
$output = print_r($array,1);
$output is a string variable, it can be logged like every other string. In pure php you can use trigger_error
Ex. trigger_error($output);
http://php.net/manual/en/function.trigger-error.php
if you need to format it also in html, you can use <pre> tag
I just wonder why nobody uses or recommends the way I prefer to debug an array:
error_log(json_encode($array));
Next to my browser I tail my server log in the console eg.
tail -f /var/log/apache2/error.log
Though it's debatable if the output is human-readable, but it's still my preferred way to read it and would look something like that:
[Tue Dec 13] [...] AH01071: Got error 'PHP message: {"form_wrapper":{"#tree":true,
"#type":"fieldset","#prefix":"","#suffix":"","#value":"","name":{"#type":
"textfield","#title":null,"#size":60,"#maxlength":60,"#required":false,
"#description":null,"#attributes":{"placeholder":"Email"},"#post":{
`"form_wrapper":{"name":"","pass":""}}}}}', referer: http://localhost/
Simple stuff:
Using print_r, var_dump or var_export should do it pretty nicely if you look at the result in view-source mode not in HTML mode or as #Joel Larson said if you wrap everything in a <pre> tag.
print_r is best for readability but it doesn't print null/false values.
var_dump is best for checking types of values and lengths and null/false values.
var_export is simmilar to var_dump but it can be used to get the dumped string.
The format returned by any of these is indented correctly in the source code and var_export can be used for logging since it can be used to return the dumped string.
Advanced stuff:
Use the xdebug plug-in for PHP this prints var_dumps as HTML formatted strings not as raw dump format and also allows you to supply a custom function you want to use for formatting.
Drupal's Devel module has other useful functions including ones that can print formatted arrays and objects to log files. See the guide at http://ratatosk.net/drupal/tutorials/debugging-drupal.html
dd()
Logs any variable to a file named “drupal_debug.txt” in the
site’s temp directory. All output from this function is appended to
the log file, making it easy to see how the contents of a variable
change as you modify your code.
If you’re using Mac OS X you can use the Logging Console to monitor
the contents of the log file.
If you’re using a flavor of Linux you can use the command “tail -f
drupal_debug.txt” to watch the data being logged to the file.
This will help you
echo '<pre>';
$output = print_r($array,1);
echo '</pre>';
EDIT
using echo '<pre>'; is useless, but var_export($var); will do the thing which you are expecting.
Syntax
print_r(variable, return);
variable Required. Specifies the variable to return information about
return Optional. When set to true, this function will return the information (not print it). Default is false
Example
error_log( print_r(<array Variable>, TRUE) );
You should be able to use a var_dump() within a pre tag. Otherwise you could look into using a library like dump_r.php: https://github.com/leeoniya/dump_r.php
My solution is incorrect. OP was looking for a solution formatted with spaces to store in a log file.
A solution might be to use output buffering with var_dump, then str_replace() all the tabs with spaces to format it in the log file.
I want to be able to add multiple PregReplace filters on a single Zend Form element.
I can add one PregReplace filter using the code below:
$word = new Zend_Form_Element_Text('word');
$word->addFilter('PregReplace', array(
'match' => '/bob/',
'replace' => 'john'
));
$this->addElement($word);
I've tried
$word = new Zend_Form_Element_Text('word');
$word->addFilter('PregReplace', array(
'match' => '/bob/',
'replace' => 'john'
));
$word->addFilter('PregReplace', array(
'match' => '/sam/',
'replace' => 'dave'
));
$this->addElement($word);
but this just meant only the second filter worked.
How do I add multiple PregReplace filters?
The problem you're facing is that the second filter will override the first one in the filters stack ($this->_filters) defined in Zend_Form_Element.
As David mentioned in the question comments, the filters stack use filter names as index ($this->_filters[$name] = $filter;) this is the reason why the second filter override the first one.
In order to resolve this problem, you can use a custom filter as follows:
$element->addFilter('callback', function($v) { return preg_replace(array('/bob/', '/sam/'),array('john', 'dave'), $v); });
This is done using an inline function(), in case you're not using PHP version 5.3 or higher, you can set your callback as follows to make it work:
$element->addFilter('callback', array('callback' => array($this, 'funcName')));
And add under your init() method in your form:
function funcName($v) {
return preg_replace(array('/bob/', '/sam/'), array('john', 'dave'), $v);
}
At last, if you want to use only the PregReplace filter, unlike Marcin's answer (the syntax is incorrect), you can still do it this way:
$element->addFilter('pregReplace', array(
array('match' => array('/bob/', '/sam/'),
'replace' => array('john', 'dave')
)));
That should do the trick ;)
Since PregReplace uses php's preg_replace function, I guess something like this would be possible (preg_replace can accepts arrays of patterns and array of corresponding replacement strings):
$word = new Zend_Form_Element_Text('word');
$word->addFilter('PregReplace', array(
'match' => array('/bob/', '/sam/'),
'replace' => array('john' , dave)
));
$this->addElement($word);
I haven't tested it though. Hope it will work.
I was unable to get the previous example to work with 'PregReplace'. I switched instead to calling it with new Zend_Filter_PregReplace(). It now works for me.
$word->addFilter(new Zend_Filter_PregReplace(array(
'match' => array('/bob/', '/sam/'),
'replace'=> array('john', 'dave'))
));
I was looking for same-response does not have a usable version
$word->addFilter(new Zend_Filter_PregReplace(new Zend_Config(array(
'match'=>array('/bob/', '/sam/'),
'replace'=>array('john', 'dave')
))));
I need to pass the value of an element to an $ajax->link without using a form/submit structure. (because I have a dynamically set number of clickable links through which I am triggering the action)
I used to do this in Ruby using the Prototype javascript function $F like this:
<%= link_to_remote "#{item.to_s}",
:url => { :action => :add_mpc },
:with => "'category=' + $F('mpc_category')" -%>
But this does not seem to work in Cakephp:
<?php echo $ajax->link(substr($vehicle['vehicles']['year'], -2),
array('action' => 'add_mpc', 'category' => '$F("mpc_category")'),
array('update' => 'results', 'position' => 'top')); ?>
PHP sees $F as a variable instead of a call to javascript. I'm not too familiar with Javascript, but is there another way to pass the value of the 'mpc_category' input element to the controller through this link? I have been looking for a couple days and can't find anyone dealing with this specific issue. Thanks for any assistance.
Edit: fixed syntax in php statement.
haven't really used cake, but I have used rails. The js part should be entirely a string. Probably something like this:
<?php echo $ajax->link(substr($vehicle['vehicles']['year'], -2),
array('action' => 'add_mpc', 'category' => "$F('mpc_category')"),
array('update' => 'results', 'position' => 'top')); ?>
I'm assuming that it tacks "$key=$value" onto the params in the ajax link. Also note you were missing a comma at the end of that second line.
After working on this for a couple days now, the best I have come up with is this:
<?php echo $ajax->link($year,
array( 'action' => 'add_row',
'category' => $category,
'product' => $product.$newpart,
array( 'update' => $summary['summary']['id']." ".$vehicle['vehicles'],
'with' => "$('app_select').serialize()")); ?>
the 'with' => "$('app_select').serialize()" being the part that grabs the values out of the form without having to submit the form.
I only needed one of the form elements, however, so this is not ideal as it passes the entire serialized form to the controller.
I would still like to be able to do this with any element, regardless of it is in a form or not, but this method doesn't seem to do that. Perhaps someone more familiar with prototype could shed some light on that.