PHP find & replace - newbie - php

So I have some text that I need to replace with some other text PLUS the original text itself.
It's for a Wordpress hook, here's the function I'm using:
function ad_content($content) {
if (is_single() || is_page()) {
$content = preg_replace('(A)','B',$content,1);
}
return $content;
}
add_filter ('the_content','ad_content');
The thing is that this will simply replace A with B, what I need is to replace A with A+B, so I guess I'll first have to find A and make it into a variable or array and then find it again, this time replacing it with the variable+another variable that has text B in it.
Does that sound right?

You can use the matched content in the replace parameter, it's available in the $1, $2, etc. for each group in the pattern
$content = preg_replace('(A)','$1 B',$content,1);
See the documentation of preg_replace

you can use str_replace
$str = "old";
$final = str_replace($str,"new".$str,$str);
echo $final;
Above code will output oldnew

This is called string building so you can search for that for more help, but as a start you can try
$content .= " additional content";
echo $content;
see the affect that has.

Use str_replace function :) Take a read here:
http://php.net/manual/en/function.str-replace.php

Related

PHP preg_replace string with value of variable

I am trying to use regex in php to find all strings that starts with "$" and replacing it with the appropriate variable. For example:
$value = "Some Value";
<b>$value</b>
Where the end result should be:
<b>Some Value</b>
This is what I have tried:
ob_start("tagreplace");
function tagreplace ( $tagreplace )
{
$value1 = "Some Value";
$pattern = '/(?<=\s)(\$[^#\s]+)(?=\s)/';
$tagreplace = preg_replace( $pattern , '<?php echo $0 ?>', $tagreplace);
return $tagreplace;
}
/* html files for combining */
include 'main_content.html';
ob_end_flush();
But this doesn't seem to work... I've tried for loops, while loops, and none of them are working. Basically I am trying to be extremely lazy and use regex to make very shorthand variables that I can put everywhere, replacing the strings like "$value" with whatever corresponding value that the variable $value has assigned to it.
I understand that /e is now deprecated so I can't use that to treat php tags as actual code. I have attempted to use preg_replace_callback but this didn't actually do anything. I'm thinking there probably isn't a way to properly do this.
It's not exactly clear what you're trying to do here, although if you take a slightly different approach with your regex you'll likely have more success. Essentially it's easier to break the pattern up into three capture groups (the start tag, the value, and the end tag)
function tagreplace ( $tagreplace ) {
$replace = "Some Value";
$pattern = '/(.+>)(.+)(<.+)/m';
$tagreplace = preg_replace( $pattern, '$1'.$replace.'$3', $tagreplace);
return $tagreplace;
}
$value = "Old Value";
echo tagreplace("<b>$value</b>");
echo "\n -- Using \$value slightly different-- \n";
$value = "<b>$value</b>";
echo tagreplace($value);
By using a more generic pattern you should be able swap out $value, regardless if it's the entire value, or if it's what is between the < > tags. When in doubt use a regex tester (linked below) and you might be able to eliminate several recursive loops, or going around in circles.
Example:
https://regex101.com/r/rW8lC6/1

Check number ID with Preg_match

i've a little problem.
I want to check the numer of post like this:
http://xxx.xxxxxx.net/episodio/168
this is part of my code, only need the number check:
[...]
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/[0-9]',trim($url))){
[...]
Can help me?
Thanks!
If you want to do it with preg_match:
$url = 'http://horadeaventura.enlatino.net/episodio/168';
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/([0-9]+)#',trim($url), $matches)){
$post = $matches[1];
echo $post;
}
So, basically: I added an end delimiter (#), changed "[0-9]" to "([0-9])+", added ", $matches" to capture the matches. Of course it can be done better and using other options than preg_match. But I wanted to make your snippet work - not rewrite it.
If you don't have your heart set on using preg_match(), you could do
$string = "http://xxx.xxxxxx.net/episodio/168";
$array = explode("/", $string);
echo end($array);
which will output
168
this is assuming the number you are looking for will always be the last section of the url string
Or, you can just check for number, on last position:
if(preg_match('#[0-9]+$#',trim($url),$match)){
print_r($match);
}

PHP Not So Simple (for me) Search & Replace using preg_match_all

im trying to create a system where a user can type in a phrase into a rich text editor such as '{item(5)}', then when the code renders the content on a page in the front end the '{item(5)}' is replaced with a snippet of code / function that uses the 5 as an unique identifier
I guess similar to how a wordpress widget would work,
im not to familiar using preg_ functions but have managed to pull out the {item(5)} and replace with a function, however the problem is it removes the rest of the content.
i might not be not be on the right lines but here is the code so far, any help would be most appreciated
$string ='This is my body of text, you should all check out this item {item(7)} or even this item {item(21)} they are great...';
if(preg_match_all('#{item((?:.*?))}#is', $string, $output, PREG_PATTERN_ORDER))
$matches = $output[0];
foreach($matches as $match){
item_widget(preg_replace("/[^0-9]/", '', $match));
}
The item_widget is just a function that uses the number to bring out a html chunk
You probably want a preg_replace_callback instead:
$output = preg_replace_callback('/\{item\((\d+)\)\}/', function($match) {
// item_widget should *return* its result for you to insert into your stream
return item_widget($match[1]);
}, $string);
This will replace the {item(n)} markers with the relevant widget results, assuming - as mentioned in the code comment - that it actually returns its code.
This works for me:
{item\(([\d]+)\)}
Checkout this eval.
so there are two parts for this question. First of all, you need to write a tag extracting part and then substitution part:
<?php
$in = "foo bar {item(1)} {item(2)}";
$out = $in;
if ($m = preg_match_all("/({item\([0-9]+\)})/is",$in,$matches)){
foreach ($matches[1] as $match){
preg_match("/\(([0-9]+)\)/", $match, $t);
$id = $t[1];
/* now we have id, do the substitution */
$out = preg_replace("/".preg_quote($match) . "/", "foo($id)", $out);
}
}
now $out should have the replaced string.

PHP:preg_replace function

$text = "
<tag>
<html>
HTML
</html>
</tag>
";
I want to replace all the text present inside the tags with htmlspecialchars(). I tried this:
$regex = '/<tag>(.*?)<\/tag>/s';
$code = preg_replace($regex,htmlspecialchars($regex),$text);
But it doesn't work.
I am getting the output as htmlspecialchars of the regex pattern. I want to replace it with htmlspecialchars of the data matching with the regex pattern.
what should i do?
You're replacing the match with the pattern itself, you're not using the back-references and the e-flag, but in this case, preg_replace_callback would be the way to go:
$code = preg_replace_callback($regex,'htmlspecialchars',$text);
This will pass the mathces groups to htmlspecialchars, and use its return value as replacement. The groups might be an array, in which case, you can try either:
function replaceCallback($matches)
{
if (is_array($matches))
{
$matches = implode ('', array_slice($matches, 1));//first element is full string
}
return htmlspecialchars($matches);
}
Or, if your PHP version permits it:
preg_replace_callback($expr, function($matches)
{
$return = '';
for ($i=1, $j = count($matches); $i<$j;$i++)
{//loop like this, skips first index, and allows for any number of groups
$return .= htmlspecialchars($matches[$i]);
}
return $return;
}, $text);
Try any of the above, until you find simething that works... incidentally, if all you want to remove is <tag> and </tag>, why not go for the much faster:
echo htmlspecialchars(str_replace(array('<tag>','</tag>'), '', $text));
That's just keeping it simple, and it'll almost certainly be faster, too.
See the quickest, easiest way in action here
If you want to isolate the actual contents as defined by your pattern, you could use preg_match($regex,$text,$hits);. This will give you an array of hits those bits that were between the paratheses in the pattern, starting at $hits[1], $hits[0] contains the whole matched string). You can then start manipulating these found matches, possibly using htmlspecialchars ... and combine them again into $code.

Delete particular word from string

I'm extracting twitter user's profile image through JSON. For this my code is:
$x->profile_image_url
that returns the url of the profile image. The format of the url may be "..xyz_normal.jpg" or "..xyz_normal.png" or "..xyz_normal.jpeg" or "..xyz_normal.gif" etc.
Now I want to delete the "_normal" part from every url that I receive. How can I achieve this in php? I'm tired of trying it. Please help.
Php str_replace.
str_replace('_normal', '', $var)
What this does is to replace '_normal' with '' (nothing) in the variable $var.
Or take a look at preg_replace if you need the power of regular expressions.
The str_ireplace() function does the same job but ignoring the case
like the following
<?php
echo str_ireplace("World","Peter","Hello world!");
?>
output : Hello Peter!
for more example you can see
The str_replace() function replaces some characters with some other characters in a string.
try something like this:
$x->str_replace("_normal","",$x)
$s = 'Posted On jan 3rd By Some Dude';
echo strstr($s, 'By', true);
This is to remove particular string from a string.
The result will be like this
'Posted On jan 3rd'
Multi replace
$a = array('one','two','three');
$var = "one_1 two_2 three_3";
str_replace($a, '',$var);
string erase(subscript, count)
{
string place="New York";
place erase(0,2)
}

Categories