String Replace In PHP - php

i have a long string like
$str = "this is [my] test [string] and [string] is very long [with] so many pwords]"
i know str_replace function, but when i replace
$str = str_replace( "[", "<a href=\"/story.php?urdu=",$str;
$str = str_replace( "]", "\"></a>",$str;
i got this result
but i want this result for each word in []
test

You should use preg_replace() for this one.
Code
<?php
function replace_matches($matches) {
$text = htmlspecialchars($matches[1]);
$url = urlencode($matches[1]);
return "{$text}";
}
$str = "this is [my] test [string] and [<script>alert(1)</script>] is very long [with] so many pwords]";
$str = preg_replace_callback("%\[(.+?)\]%", "replace_matches", $str);
echo $str;
?>
Working Example

$str = preg_replace_callback(
'/\[([^\]]*)\]/',
function($matches) {
return sprintf('%s',
urlencode($matches[1]),
htmlspecialchars($matches[1]));
},
$str);

Related

Using preg_replace to get $_GET variables

I made the following PHP function:
<?php
function convertGET($str) {
$regex = '/GET:+([a-zA-Z0-9_]+)/';
$str = preg_replace($regex, $_GET["$1"], $str);
return($str);
}
$string = "foobar: GET:foobar";
$string = convertGET($string);
echo $string;
?>
The function is suppost to get a string and replace something like:
GET:foobarwith the $_GET variable "foobar".
Use preg_replace_callback() instead:
<?php
$input = array("foobar" => "Some other string");
$regex = '~GET:([a-zA-Z0-9_]+)~';
$string = "foobar: GET:foobar";
$string = preg_replace_callback($regex,
function($matches) use ($input) {
return $input[$matches[1]];
},
$string);
echo $string;
// output: foobar: Some other string
?>
See a demo on ideone.com.

Replace content between two tags

I want to replace all content between ( and ), using php.
my string:
$string = "This is a (string)";
the required output is:
$string = "This is a";
my code doesn't works:
$string = "This is a (string)";
$search = "/[^(](.*)[^)]/";
$string = preg_replace($search, "", $string);
echo $string; // output is ")"
$result = preg_replace('/\(.+?\)/sm', 'Put your text here', $string);
Try this code
Or to save () add them to replacement
$page = preg_replace('/\(.+?\)/sm', '(Put your text here)', $page);
This should work for you:
<?php
$string = "This is a (string)";
echo preg_replace("/\([^)]+\)/","",$string);
?>
Output:
This is a
Just change that:
$search = "/ *\(.*?\)/";

How to create a function that can transform the last word into Uppercases?

How do i create a function replaceMe() in php that would turn:
$str = 'This is a very long string';
into:
'This is a very long STRING?'
can someone help me?
You apparently want to do a regular expression substitution, anchored at the end of the line. Use preg_replace:
$str = 'This is a very long string';
# This is a very long LINE
echo preg_replace("/string$/", "LINE", $str);
For a general case, you can provide a callback instead of a replacement string, and simply uppercase the matched substring with preg_replace_callback:
$str = 'This is a very long blah';
function word_to_upper($match) {
return strtoupper($match[1]);
}
# This is a very long BLAH
echo preg_replace_callback("/(\w+)$/", "word_to_upper", $str);
If you're using PHP 5.4 or greater, you can supply the callback as an anonymous function:
echo preg_replace_callback("/(\w+)$/", function ($match) {
return strtoupper($match[1])
}, $str);
This works:
$str = 'This is a very long string';
echo $str."<br/>";
function replaceMe($str = "")
{
$words = explode(" ",$str);
$totalwords = count($words)-1;
$lastword = $words[$totalwords];
$words[$totalwords] = strtoupper($lastword);
$str = implode(" ",$words);
return $str;
}
echo replaceMe($str);
?>
Output:
This is a very long string
This is a very long STRING
$str = 'This is a very long string.';
function lastWordUpper($str){
$temp = strrev($str);
$last = explode(" ", $temp, 2);
return strrev(strtoupper($last[0]). ' ' .$last[1]) ;
}
echo lastWordUpper($str);

php regex bbcode returns blank

I have this bbcode tag "remover" which should remove bbcode tags from my test text.
All i get is nothing. Just blank page where should be the text replaced with html tags.
Whats wrong with it. And maybe anyone have some better script to share.
$str = 'This [b]is just[/b] a [i]test[/i] text!';
function forum_text($str)
{
$str = htmlspecialchars($str);
$str = preg_replace( "#\[url\](?:http:\/\/)?(.+?)\[/url\]#is", "$1", $str );
$str = preg_replace( "#\[img\](?:http:\/\/)?(.+?)\[/img\]#is", "<img src=\"http://$1\" />", $str );
$str = preg_replace( "#\[b\](.+?)\[/b\]#is", "<strong>$1</strong>", $str );
$str = preg_replace( "#\[i\](.+?)\[/i\]#is", "<i>$1</i>", $str );
$str = preg_replace( "#\[u\](.+?)\[/u\]#is", "<u>$1</u>", $str );
return $str;
}
The following is your code, with some code in front of it (to make sure any errors are shown) and some code at the back (that actually calls your function).
If this doesn't work for you, your problem is not here, unless you don't have a working PCRE.
error_reporting(-1); ini_set('display_errors', 'On');
$str = 'This [b]is just[/b] a [i]test[/i] text!';
function forum_text($str)
{
$str = htmlspecialchars($str);
$str = preg_replace( "#\[url\](?:http:\/\/)?(.+?)\[/url\]#is", "$1", $str );
$str = preg_replace( "#\[img\](?:http:\/\/)?(.+?)\[/img\]#is", "<img src=\"http://$1\" />", $str );
$str = preg_replace( "#\[b\](.+?)\[/b\]#is", "<strong>$1</strong>", $str );
$str = preg_replace( "#\[i\](.+?)\[/i\]#is", "<i>$1</i>", $str );
$str = preg_replace( "#\[u\](.+?)\[/u\]#is", "<u>$1</u>", $str );
return $str;
}
echo forum_text($str);

replace everything except specific words in PHP

Is it possible to use php's preg_replace to remove anything in a string except specific words?
For example:
$text = 'Hello, this is a test string from php.';
I want to remove everything except "test" and "php" so it will be:
$text will be 'test php'
You could always use a callback. Under PHP 5.3:
$keep = array('test'=>1, 'php'=>1);
$text = trim(
preg_replace(
'/[^A-Za-z]+/', ' ',
preg_replace_callback(
'/[A-Za-z]+/',
function ($matched) use (&keep) {
if (isset($keep[$matched[0]])) {
return $matched[0];
}
return '';
}, $text
) ) );
Alternatively:
$text =
array_intersect(
preg_split('/[^A-Za-z]+/', $text),
array('test', 'php')
);
$text = 'Hello, this is a test string from php.';
$words = preg_split('~\W~', $text, -1, PREG_SPLIT_NO_EMPTY);
$allowed_words = array('test'=>1, 'php'=>1);
$output = array();
foreach($words as $word)
{
if(isset($allowed_words[$word]))
{
$output[] = $word;
}
}
print implode(' ', $output);

Categories