Keys, and values mysql.
$valores[$codigo] = "<img src=\"template/" . $template . "/smiles/" . $smile . "\" border=\"0\"/>";
$arrayKeys = array_keys($valores);
$arrayValues = array_values($valores);
return preg_replace($arrayKeys, $arrayValues, $coment);
error, Warning: preg_replace() [function.preg-replace]: No ending delimiter ':' found.
You may want to use str_replace() instead.
Edit :
You just need to replace preg_replace by str_replace :
return str_replace($arrayKeys, $arrayValues, $coment);
See the documentation here str_replace()
preg_replace() - Perform a regular expression search and replace
If I understand correctly you want to replace :) with smiles images so you can do that like this:
<?php
$search = array(":))",":)");
$replace = array("<img src=\"template/" . $template . "/smiles/laugh.jpg\" />","<img src=\"template/" . $template . "/smiles/smile.jpg\" />");
str_replace($search, $replace, $comment);
?>
Related
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.
<?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 am still relatively new to Regular Expressions and feel My code is being too greedy. I am trying to add an id attribute to existing links in a piece of code. My functions is like so:
function addClassHref($str) {
//$str = stripslashes($str);
$preg = "/<[\s]*a[\s]*href=[\s]*[\"\']?([\w.-]*)[\"\']?[^>]*>(.*?)<\/a>/i";
preg_match_all($preg, $str, $match);
foreach ($match[1] as $key => $val) {
$pattern[] = '/' . preg_quote($match[0][$key], '/') . '/';
$replace[] = "<a id='buttonRed' href='$val'>{$match[2][$key]}</a>";
}
return preg_replace($pattern, $replace, $str);
}
This adds the id tag like I want but it breaks the hyperlink. For example:
If the original code is : Link
Instead of <a id="class" href="http://www.google.com">Link</a>
It is giving
<a id="class" href="http">Link</a>
Any suggestions or thoughts?
Do not use regular expressions to parse XML or HTML.
$doc = new DOMDocument();
$doc->loadHTML($html);
$all_a = $doc->getElementsByTagName('a');
$firsta = $all_a->item(0);
$firsta->setAttribute('id', 'idvalue');
echo $doc->saveHTML($firsta);
You've got some overcomplications in your regex :)
Also, there's no need for the loop as preg_replace() will hit all the instances of the search pattern in the relevant string. The first regex below will take everything in the a tag and simply add the id attribute on at the end.
$str = 'Link' . "\n" .
'Link' . "\n" .
'Link';
$p = "{<\s*a\s*(href=[^>]*)>([^<]*)</a>}i";
$r = "<a $1 id=\"class\">$2</a>";
echo preg_replace($p, $r, $str);
If you only want to capture the href attribute you could do the following:
$p = '{<\s*a\s*href=["\']([^"\']*)["\'][^>]*>([^<]*)</a>}i';
$r = "<a href='$1' id='class'>$2</a>";
Your first subpattern ([\w.-]*) doesn't match :, thus it stops at "http".
Couldn't you just use a simple str_replace() for this? Regex seems like overkill if this is all you're doing.
$str = str_replace('<a ', '<a id="someID" ', $str);
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'); ?>
I have this URLs...
$output = "href=\"/one/two/three\"
href=\"one/two/three\"
src=\"windows.jpg\"
action=\"http://www.google.com/docs\"";
When I apply the regular expression:
$base_url_page = "http://mainserver/";
$output = preg_replace( "/(href|src|action)(\s*)=(\s*)(\"|\')(\/+|\/*)(.*)(\"|\')/ismU", "$1=\"" . $base_url_page . "$6\"", $output );
I get this:
$output = "href=\"http://mainserver/one/two/three\"
href=\"http://mainserver/one/two/three\"
src=\"http://mainserver/windows.jpg\"
action=\"http://mainserver/http://www.google.com/docs\"";
How you can modify the regular expression to prevent this: http://mainserver/http://www.google.com/ ???????
Try
$output = preg_replace( "/(href|src|action)\s*=\s*["'](?!http)\/*([^"']*)["']/ismU", "$1=\"" . $base_url_page . "$2\"", $output );
I have simplified your regex and added a lookahead that makes sure the string you're matching doesn't start with http. As it is now, this regex allows neither single nor double quotes inside the URL.
$output = preg_replace( "/(href|src|action)\s*=\s*[\"'](?!http)(\/+|\/*)([^\"']*)[\"']/ismU", "$1=\"" . $base_url_page . "$3\"", $output );