How could replace from the PHP String - php

I wan't to replace
[a href='url']link[/a]
to
<a href='url'>link</a>
I am using $line = str_replace("[a href='+(.*)+']", "<a href='+(.*)+' >", $line); is not working.

Why not just use:
$search = array('[', ']');
$replace = array('<', '>');
$line = str_replace($search, $replace, $line);

You have to use a regular expression to do this
$line = preg_replace('~\\[a +href=\'([^\']+)\'\\]([^\\[]+)\\[/a\\]~', '$2', $line);

simply use
$string = str_replace(array('[', ']'), array('<', '>'), $string);

This is a great tutorial http://www.youtube.com/watch?v=x9VLWlQhNtM it shows you how to make a small templating engine and it covers what your asking

Try this :
$str = "[a href='url']link[/a]";
$new_str = preg_replace('/\[a href=\'(.*)\'\](.*)\[\/a\]/','<a href=\'$1\'>$2</a>',$str);
echo $new_str;

Related

preg_replace: all after first "-"

I have:
$text = "1235-text1-text2-a1-780-c-text3";
How can I get this with preg_replace? It is necessary to redirect 301.
"text1-text2-a1-780-c-text3"
for no use regex you can try
trim(strstr($text, '-'),'-');
No Regex needed:
$result = substr($text, strpos($text, '-')+1);
Or:
$result = trim(strstr($text, '-'), '-');
This will work
[^-]*-
Regex Demo
PHP Code
$re = "/[^-]*-/";
$text = "1235-text1-text2-a1-780-c-text3";
$result = preg_replace($re, "", $text, 1);
Ideone Demo
Or use preg_match
<?php
$text = "1235-text1-text2-a1-780-c-text3";
preg_match("%[^-]*-(.*)%",$text, $matchs);
var_dump($matchs[1]);
// Output "text1-text2-a1-780-c-text3"
?>
As you wanted, using preg_replace:
$re = '/^([\w]*-)/';
$str = "1235-text1-text2-a1-780-c-text3";
$match = preg_replace($re, "", $str);
var_dump($match);
An alternative using preg_match:
$re = '/-(.*)/';
$str = "1235-text1-text2-a1-780-c-text3";
preg_match($re,$str,$matches);
var_dump($matches[1]);

php replace paragraph to newline

how to replace <p>hello</p> <p>world</p> to hello<br />world <br />
I've tried searching on stack but there is no matched result.
You could do this by using str_replace() function.
For instance:
$string = "<p>hello</p> <p>world</p>";
$string = str_replace('<p>', '', $string);
$string = str_replace('</p>', '<br />' , $string);
I try this myself and get what I expected
$pattern = '/<p>(\w+)\<\/p>/';
$subject = '<p>hello</p><p>world</p>';
$replacement = '${1}<br/>';
$out = preg_replace($pattern, $replacement, $subject);
I just wonder which is better regex or str_replace
I wrote a better solution, hope everybody can see it helpful and maybe improve it
$pattern = '/<p(.*?)>((.*?)+)\<\/p>/';
$replacement = '${2}<br/>';
$subject = 'html string';
$out = preg_replace($pattern, $replacement, $subject);
Use this to prevent breaking the first and last <p></p> :
$string = str_replace($string, '</p><p>', '');
But if a space comes between the tags, it won't work.
<?php
$str = '<p>hello</p> <p>world</p>';
$replaceArr = array('<p>', '</p>', '</p> <p>');
$replacementArr = array('', '', '<br />');
$str = str_replace($replaceArr, $replacementArr, $str);
echo $str;
?>
Try above code.

Regular expression for finding multiple patterns from a given string

I am using regular expression for getting multiple patterns from a given string.
Here, I will explain you clearly.
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
The above is my code.
Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??
Now, I need a regular expression that gives me patterns like
about_us, about-us, aboutus as output if i give about us as input.
Is this possible to do.
Please help me in that.
Thanks in advance!
And finally, my answer is
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
You need to do a loop to handle multiple possible outputs :
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
You can try without regex:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
If you put special characters into an array:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
Also you can use just str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.
e.g.
preg_replace('/\W+/', '-', $string);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
I am not sure that regexes are the good tool for that. However you can simply define this kind of function:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
Matches any character that is not a word character
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
in case its just that... you would get problems if it's a longer string :)

Reversion Strings and replace a character - RegEx with Php

I have a doubt again on RegEx in Php.
Assume that I have a line like this
716/52 ; 250/491.1; 356/398; 382/144
I want the output to be
Replace all semi-colon with comma. I think I can do this using
$myline= str_replace(";", ",", $myline);
Interchange the numbers and replace '/' with a comma. That is, 716/52 will become 52,716. This is where I get stuck.
So, the output should be
52,716 , 491.1,250, 398,356, 144,382
I know that using sed, I can achieve it as
1,$s/^classcode:[\t ]\+\([0-9]\+\)\/\([0-9]\+\)/classcode: \2\,\1/
But, how do I do it using preg_match in php?
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', 'reverse', $str);
function reverse($matches)
{
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}
var_dump($res);
And working sample: http://ideone.com/BeS9j
UPD: PHP 5.3 version with anonymous functions
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}, $str);
var_dump($res);
As an alternative to Regexen you could try this:
echo join(', ', array_map(
function ($s) { return join(',', array_reverse(explode('/', trim($s)))); },
explode(';', $string)));
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = preg_replace('(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)', '$2,$1', $str);
$str = str_replace(';', ',', $str);
Uses two capture groups, replacing them in reverse order. See it here.

How to lowercase only HTML elements

How can I lowercase all HTML elements but not their attributes or attribute values?
I found a lot of examples like
$newString = preg_replace("/<[^>]+>/e", "strtolower('\\0')", $oldString);
But it lower cases everything, not just the tags.
Try the following:
$newString = preg_replace( "/<([^> ]+)/e", "strtolower('\\0')", $oldString )
how about:
$oldString = "<H1 CLASS='abc'>HGKJHG</H1>\n< P ClAsS='AbC123'>HKJGHG</P>";
$newString = preg_replace("~(</?\s*\w+)~e", "strtolower('\\1')", $oldString);
echo $newString,"\n";
output:
<h1 CLASS='abc'>HGKJHG</h1>
< p ClAsS='AbC123'>HKJGHG</p>
$newString = preg_replace("/</?\w+/e", "strtolower('\\0')", $oldString);
function change_case_tags($string, $action = 'mb_strtolower')
{
$string = preg_replace('!<([^> ]+)!e', "$action('\\0')", $string);
if(strpos($string, '=') !== false)
{
return $string = preg_replace('!(?:\s([^\s]+)=([\'"])?(.+)\\2)!Uie', "$action(' \\1').'='.str_replace('\\\\\\', '', '\\2').'\\3'.str_replace('\\\\\\', '', '\\2').''", $string);
}
return $string;
}

Categories