I want to replace the first and last words and sentences .
I use this code.
$text = ' this is the test for string. ';
echo $text = str_replace(" ", "", $text);
when i have use replace code .
all space is deleted and repalsed.
any body can help me?!
i want get this:
this is the test for string.
You probably want the trim function here:
$text = ' this is the test for string. ';
echo '***' . trim($text) . '***';
***this is the test for string.***
Just to round out this answer, if you wanted to accomplish the same thing using a replacement, you could do a regex replace as follows:
$out = preg_replace("/^\s*|\s*$/", "", $text);
echo '***' . $out . '***';
***this is the test for string.***
This approach might a good starting point if you wanted to do a regex replacement with perhaps slightly different logic.
Related
<?php
echo "I'm currently listening to</a> <a href='http://last.fm/artist/" . str_replace(" ","+",$artist) . "/_/" . str_replace(" ","+",$currenttrack) . "'>" . $currenttrack . "</a>";
?>
Above is my code. I'm trying to use str_replace() again on $artist and $currenttrack like:
str_replace("'","%27",$artist) and str_replace("'","%27",$currenttrack)
because the apostrophe doesn't go through correctly and messes with my code, but when I use it first with the spaces, it's already passed and won't change again.
What can I do?
If you want to do multiple replacements on the same string, you can pass arrays to str_replace:
str_replace(array(" ", "'"), array("+", "%27"), $artist)
However, when creating URL parameters, you shouldn't do the replacements yourself. You should use urlencode, and it will do all the necessary encodings.
Try this. It also makes your code more readable. Also, your anchor tags aren't formatted correctly.
$artist = str_replace(' ', '+', $artist);
$track = str_replace(' ', '%27', $currenttrack);
echo 'I\'m currently listening to ' . $track . '';
If I understood your question correctly, you are trying to replace spaces by + and ' by %27 in the two strings. To achieve this, you have to apply str_replace() on the result of the first operation. If $input is the original string, use:
$intermediate = str_replace(" ", "+", $input);
$result = str_replace("'", "%27", $intermediate);
There is a built in function to do the same you are trying to do: urlencode
$currenttrack = $artist = "X' xx WWW' w";
$url = "http://last.fm/artist/" . $artist . "/_/" . $currenttrack;
echo urlencode($url); // http%3A%2F%2Flast.fm%2Fartist%2FX%27+xx+WWW%27+w%2F_%2FX%27+xx+WWW%27+w
I can understand most PHP code by just reading it, but I've never understood how preg_replace is used, so I've only been copying other peoples codes to get what I want.
Now I need to add linebreaks in it, and I've tried multiple combinations but I can't figure out how to use it.
This is my current code:
$textbr = nl2br($text);
$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($textbr)));
echo substr($output,0,870);
echo "...</p>";
So how would I add line breaks in this part of the code? I need it to both output the linebreak but then make the next letter a capitalized one.
Line breaks are: \n for NewLine, and \r for Return carriage.
RegExp is fun, I advise learning more about it http://www.regular-expressions.info/ :)
To anyone wondering. I solved it by just randomly trying myself towards the solution.
SOLUTION:
$textbr = nl2br($text);
$output = preg_replace_callback(
'/([.!?\r?\n)])\s*(\w)/',
function ($matches) {
return strtoupper($matches[1] . ' ' . $matches[2]);
},
ucfirst(
strtolower($textbr)
)
);
I need help with my PHP, I'm using str_ireplace() and I want to filter something out and replace it with what I have.
I find it hard to explain what I am talking about so I will give an example below:
This is what I need
$string = "<error> " . md5(rand(0, 1000)) . time() . " </error> Test:)";
then I want to remove and replace the whole <error> .... </error> with nothing.
So the end outcome should just print 'Test:)'.
Your question is not perfectly clear, but I believe I may understand what you are asking. This code may do the trick:
$string = " " . md5(rand(0, 1000)) . time() . " Test:)";
$newstring = preg_replace("/.*?\ /i", "", $string);
This uses regular expressions to filter out everything that comes before the space (and also removes the space)
I have some HTML code like this:
<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf&sa=U&ei=sf0JUrmjIc3Nswb154CgDQ&ved=0CCkQFjAA&usg=AFQjCNGfXg_9x83U3pYr6JfkJcWuXv8X0Q">
I need to clean my code to get something like this
<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf">
using preg_replace.
My code is the following:
$serp = preg_replace('&sa=(.*)" ', '" ', $serp);
and it doesn't work.
BTW i need to restrict search with preg_replace until the FIRST entrance, i.e. i need to replace all html from &sa= to the FIRST ", but now it search from &sa= to the LAST "...
You're missing the regex delimiters.
$serp = preg_replace('/&sa=(.*)" /', '" ', $serp);
will give you this.
You missed the delimiter.
So your code looks like:
$serp = preg_replace('/&sa=(.*)" /', '" ', $serp);
okay, if you want to delete everything till the first quote then you can try the following instead of regex:
$temp = substr($serp,strpos($serp,'&sa='),strpos($serp,'"',strpos($serp,'&sa=')));
$serp = str_replace($temp,"",$serp);
Just another regex to do it :)
$text = '<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf&sa=U&ei=sf0JUrmjIc3Nswb154CgDQ&ved=0CCkQFjAA&usg=AFQjCNGfXg_9x83U3pYr6JfkJcWuXv8X0Q" target="_blank">';
$text = preg_replace('/(&sa=[^"]*)/', '', $text);
echo $text;
// Output:
<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf" target="_blank">
You can try it HERE (thks to hjpotter92 for this tool)
I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters \/:*?"<>|, without doing a str_replace for each.
Like this:
str_replace(array(':', '\\', '/', '*'), ' ', $string);
Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:
str_replace([':', '\\', '/', '*'], ' ', $string);
str_replace() can take an array, so you could do:
$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);
Alternatively you could use preg_replace():
$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:
print str_replace(
array("search1","search2"),
array("replace1", "replace2"),
"search1 search2"
);
// Output: replace1 replace2
str_replace(
array("search","items"),
array("replace", "items"),
$string
);
If you're only replacing single characters, you should use strtr()
You could use preg_replace(). The following example can be run using command line php:
<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>
Output:
$s2: "the string "
I had a situation whereby I had to replace the HTML tags with two different replacement results.
$trades = "<li>Sprinkler and Fire Protection Installer</li>
<li>Steamfitter </li>
<li>Terrazzo, Tile and Marble Setter</li>";
$s1 = str_replace('<li>', '"', $trades);
$s2 = str_replace('</li>', '",', $s1);
echo $s2;
result
"Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",
I guess you are looking after this:
// example
private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';
...
public function templateFor(string $type, string $language): string
{
return \str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
}
In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.
<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>