I want to use PHP to replace javascript functions in HTML documents. For example:
original:
function my_function(hey) {
do stuff
}
new:
function new_function(hi) {
do different stuff
}
I was thinking of using regular expressions with the ereg_replace function, but I'm not sure if this is the best approach. The code in each function is pretty long... plus regex looks very daunting to me at the moment. Any suggestions?
This is the kind of thing that perl is built for. Spend a day learning how to slurp in files and take a good look at the many regex tools out there, and you'll have yourself a script that you can modify to use in the future, if need be, but is otherwise throwaway, which is good, since you probably wrote it crappily, being your first one and all.
Looks like you trying to do something pointless. Put a new function and call it. Just do no use the old one, once you anyway want to replace the entire body with it's name.
Related
Is there any fast (regex-based?) method to replace all smileys in a text, each by an unique corresponding identifier? For example, the first occurrence of :) should be replaced by smiley1, the :)) by smiley2 and another occurrence of :) by smiley1 again? Furthermore, the identifyier should be the same using different text for input
Any potential combination of the typical symbols (<5 chars?) such as :;-()&%}{[]D<>30_o should be recognizable.
Can this be done without a generating a large array of all combinations? In case, how?
Are you looking for preg_replace_callback()? You can even use closures in php 5.3. I am not clear on what the objective is, so at this point this is the best I can provide, if you can clarify, then maybe I can see what I can come up with for sample code.
edit, here's an example from the PHP manual. Doesn't help in this case specifically, but if you just change the regex, the function and the string (basically everything, lol), then it will do the job:
<?php
echo preg_replace_callback('/-([a-z])/', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>
I don't understand why you can't do:
str_replace(":))","<img src=\"smiley1.jpg\">",$STRING)
str_replace(":)","<img src=\"smiley2.jpg\">",$STRING)
etc... seems to be the most simple solution and logical
Obviously, it cannot be done by using such a str_replace. How would you fetch a ":)))" or maybe a "-.-" which is also not present in your list? Enumerating all potential smileys is a hard task, resulting in n!/(n-k)! candidates. Here, in the example provided above n=18 and k=5...
Thus, I'm asking for a way to use a regex - but I don't how to replace each combination of chars which is intended to represent a smiley each time by the same text.
Idea: is it possible to use a callback function in combination with a hash?
Yeah, Tim! That is exactely what came into my mind when writing the last post. So the solution is
<?php
echo preg_replace_callback("/([\)\(\[\]<>#-\.:;*+{}]{2,9})/", function ($match) {
return " ".md5($match[1])." ";
}, ':::-) :-)) nope (yeah) cool:) }:)');
?>
Thanks!
I'm looking at the PHP code for the interspire shopping cart and they make extensive use of template variables such as %%GLOBAL_variables%% and %%variable%%.
I haven't seen those before and I'm trying to understand how they are defined and used. Does anyone know what template engine is involved and any documentation on it?
thanks
I've used %% as "delimiters" for my own homegrown templating engine. There is nothing special about it, they are just characters that will prevent any unwanted replacements since it is very unlikely they will occur naturally. Some engines use {keyword}, like Smarty.
As an example, you can do a quick search/replace with an associative array of data.
$data_replace = array('%%GLOBAL_variable%%'=>'some data',
'%%variable1%%'=>'different data',
'%%variable2%%'=>'limited time only!');
//Perform the search and replace
$output = str_replace(array_keys($data_replace), $data_replace, $template_text);
As a guess it looks like a home grown solution.
That said, it would be pretty easy to re-create something like this by doing something like:
Load the template file into a
string.
Grab all occurances of '%%xxx%%'.
(I'm guessing the '%%' are just
handly delimiters.)
Convert the first '%%' to '$_' if
the occurance begins with '%%GLOBAL'
or '$' otherwise.
Once all that's done evaluate the resultant string. (eval)
Additionally, it would be possible to include variables within the scope of the evaluation using extract.
Irrespective, I'd have thought you should be able to confirm this by having a hunt around in the code.
I have a php function that I wish to reduce even further.
<?='Testing'?>
Is there a way to reduce this any further?
write Testing without the php tags. php will only interpret code between php tags, everything else will be outputted without any further processing.
Use a shorter word? ;)
Or put it outside the PHP tags (effectively starting and stopping the PHP goodiness).
?>Testing<?
Incidentally - I'm not overly sure what you want to achieve by "shortening". Do you want to make it faster, use less characters? From that example there - I'm not sure you're going to gain a whole lot from any of these examples.
You can assign the value you'd like printed to a short variable name before the output of the script:
<?php
$a = 'Testing';
?>
Then echo out that variable in the output:
<?=$a?>
Can't get any shorter than that.
I'm creating a very simple PHP templating system for a custom CMS/news system. Each article has the intro and the full content (if applicable). I want to have a conditional of the form:
{continue}click to continue{/continue}
So if it's possible to continue, the text "click to continue" will display, otherwise, don't display this whole string. So far, it works like this: if we can continue, remove the {continue} tags; otherwise, remove the whole thing.
I'm currently using preg_match_all to match the string in the second case. What is the best function for removing the matched text? A simple str_replace, or something else?
Or is there a better way to implement this overall?
Why not use preg_replace_callback?
Specifically:
preg_replace_callback('!\{continue\}(.*)\{/continue\}!Us', 'replace_continue', $html);
function replace_continue($matches) {
if (/* can continue */) {
return $matches[1];
} else {
return '';
}
}
I find preg_replace_callback to be incredibly useful.
Sorry I know people have been ridiculing this kind of answer, but just use Smarty. Its simple, stable, clever, free, small and cheap. Spend an hour learning how to use it and you will never look back.
Go to www.smarty.net
For PHP templating systems the proper way is to parse the template (using state machine or at least preg_split), generate PHP code from it, and then use that PHP code only. Then you'll be able to use normal if for conditional expressions.
Regular expressions aren't good idea for implementing templates. It will be PITA to handle nesting and enforce proper syntax beyond basic cases. Performance will be very poor (you have to be careful not to create backtracking expression and even then you'll end up scanning and copying KBs of templates several times).
I am new to programming and learning with Wordpress.
the_title(); //outputs the title of the page
I want to capture the title of the page into a string variable so I can manipulate it with strtolower and str_replace functions.
The only way I have gotten it to work is with output buffering.
ob_start();
the_title();
$result = ob_get_clean();
echo str_replace(" ","-",strtolower($result));
/*there has got to be an easier way....
i dont fully understand why */
str_replace(" ","-",strtolower(the_title()));
What am I doing wrong?
If what you really are looking for is the wp_title function, the 2nd argument it takes is a boolean on whether or not it should display it or return it. Pass it false so it will return it to the var, then you can do this:
$mytitle = wp_title(null, false);
Otherwise, your only option is to find the function you're looking for and modify the source code.
There is no easier way. Your function does not return the string, it prints it, therefore you will have to use output buffering if you want to capture the output.
It's the difference between f1() and f2() in the following example.
// Returns a string, prints nothing.
function f1() {
return "String";
}
// Prints a string, returns nothing.
function f2() {
echo "String";
}
Wordpress is a HORRIBLE app to learn how to program from. It uses these global functions that "just work" but they do very specific tasks "inside 'The Loop'". As I say, this is a horrible example of what good code should be.
Thankfully (for you) there are other functions that just return the part you're looking for. Rather than me just writing what you need, you can read a full listing here. Take care that you note down which must be within the mythical Loop and which you can use anywhere.
As it happens there are even more ways to get the title, but I was really imagining for this example you would do something like:
$this_post = get_post($post); // I *think* $post is the post ID inside the loop though I could be wrong
echo $this_post->post_title;
But as another poster (correctly) says you can use a fairly simple wp_title() function to grab the current loop title.
This brings me back to perhaps wanting to explain why learning programming from Wordpress is a bad idea. They have so many damned way of doing the same damned thing that it's almost impossible to keep on top of things.
A blog is a really simple set of data (even moreso in WP's case because it isn't fully normalised) but rather than just having one way to output a title <?php echo $post->title; ?> you have umpteen ways, all doing subtly different things.
If you really want to learn how to program (instead of hacking your way around the crap that is the WP internals), creating a simple blog engine is fairly quick and fun... It's certainly how a lot of people get into a new language or framework.
And if you really want to have fun, have a look at Django.
Enough of the Wordpress rant. If you're fighting something like this in the future that doesn't have 100 ways of doing it, I really wouldn't recommend output-buffer-capturing. It uses up a whole buttload of resources for something relatively simple.
The easiest way can be as simple as just taking the source for the original function, sticking it in a new function and replacing the echo with return.
Just note there may be some database connectivity to handle that returning prematurely may break... So if the echo isn't the last statement, instead of returning right there, store the string as a variable and return at the end of the function.
just figured Id share my final solution with you guys.
This was to give my body tags unique id's in wordpress.*/
$title =wp_title(null,false);
echo strtolower(str_replace(' ','-',ltrim($title)));
//without the ltrim() 2 dashes are created before the title.
Almost every 'the_*' function in Wordpress has a 'get_the_*' counterpart. So, you just have to use
echo str_replace(" ","-",get_the_title());
And it's going to work like a charm. there's also get_the_excerpt(), get_the_content() and the_permalink() which somehow breaks the naming convention (God knows how many times I've written "get_the_permalink()" and got frustrated on why it didn't work)
Cheers!