Remove text inside of text from a larger string with PHP - php

What I'm trying to do is, if it exists, remove an occurrence of text inside a 'shortcode', eg: Here's some content [shortcode]I want this text removed[/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content.
It seems like a pretty simple thing to do but I can't figure it out.. =/
The shortcode will only show up once in the entire string.
Thanks in advance for help.

Try this:
$var = "Here's some content [shortcode]I want this text removed[/shortcode] Some more content";
$startTag = "[shortcode]";
$endTag = "[/shortcode]";
$pos1 = strpos($var, $startTag) + strlen($startTag);
$pos2 = strpos($var, $endTag);
$result = substr_replace($var, '', $pos1, $pos2-$pos1);

It's very easy to do with preg_replace(). For your purpose, use /\[shortcode\].*\[\/shortcode\]/ as pattern.
$replace = "[shortcode][/shortcode]";
$filteredText = preg_replace("/\[shortcode\].*\[\/shortcode\]/", $replace, $yourContent);
See http://php.net/manual/en/function.preg-replace.php for more details.

One can use strpos() to find the position of [substring] and [/substring] in your string and replace the text with a whitespace via substr_replace()

if you do not want to bother with regular expessions:
if you do have the [shortcode] tag inside the string, than it is really no problem: just use a nested use of substr:
substr($string,0,strpos($string,'[substring]')+11)+substr($string,strpos($string,'[/substring]'),strlen($string))
where the first substr cuts the string to the start of the string to cut and the second adds the remaining stuff of the string.
see here:
http://www.php.net/manual/en/function.substr.php
http://www.php.net/manual/en/function.strpos.php

use regex in php to get rid of it.
preg_replace (shortcode, urText, '', 1)

$string = "[shortcode]I want this text removed[/shortcode]";
$regex = "#\[shortcode\].*\[\/shortcode\]#i";
$replace = "[shortcode][/shortcode]";
$newString = preg_replace ($regex, $replace, $string, -1 );

$content = "Here's some content [shortcode]I want this text removed[/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content";
print preg_replace('#(\[shortcode\])(.*?)(\[/shortcode\])#', "$1$3", $content);
Yields:
Here's some content [shortcode][/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content

Related

PHP replace string for other string

I have a doubt, it may be something simple but I have no knowledge to solve it.
I get a string in php
$ string = "[link = someUrl] Text [link]"
And I would like to turn this string into:
"<a href='someUrl'> Text <a/>"
How do I change the URL? and How Can I do the opposite?
Remember that the string belongs to a text with more strings of these gifts.
Short preg_replace solution:
$s = "[link=someUrl] Text [/link]";
$result = preg_replace('#\[[^=]+=([^]]+)\]([^[]+).*#', '<a href=\'$1\'>$2</a>', $s);
print_r($result);
The output (as web page source code):
<a href='someUrl'> Text </a>
You can use the following code
function transformText($string) {
preg_match("/\[link\=([^\]]*)\](.*?)\[\/link]/", $string, $matches);
$someUrl = $matches[1];
$text = $matches[2];
$newString = "<a href='$someUrl'>$text</a>";
return $newString;
}
$string = "[link=someUrl] Text [/link]"; // Test string
echo (transformText($string));
Live demo for the regex used : https://regex101.com/r/tzVfmH/4
Note : The above code works only if there's a single [link], [/link] pair.
If multiple occurrences are to be handled then its better to use regex search and replace, using php's preg_replace as suggested in RomanPerekhrest's answer.

Regex which will find string from content and replace with HTML tag

I have a content like this.
"Test with the dummy content. Another dummy content."
I want regex where If I pass specific string and specific html tag then It will replace string with tag. For ex.
function strReplace($content, $string, $tag)
{
// $output = regex function ...
}
If I call method like strReplace($content, 'dummy', 'b');
Output should be:
"Test with the <b>dummy</b> content. Another <b>dummy</b> content."
Thanks in advance
You're searching for preg_split: http://php.net/manual/en/function.preg-split.php
You can split on the regex, receive the fragment and then insert after the first and before the last element your tags. This is probably (depending on your context) even so possible with just str_split.
Find solution.
Tried something and it works. Using regex like
// $tag = '<b>'; or $tag = 'b';
$tag = str_replace('<', '', str_replace('>', '', $tag));
$output = preg_replace(array('/'.$string.'/'), array('<'.$tag.'>'.$string.'</'.$tag.'>'), $content);
Thanks for help still suggestions are always welcome.

Using regex to retrieve link between special characters in a string

I want to retrieve the link between (Ampersand)lt; and (Ampersand)gt; from the below string.
<http://www.test.com>
I then want to replace the above string with the link. The string is in a file so I'm using the following code to replace the string in the file:
$contents = file_get_contents($path);
$contents = str_replace($id."\n", "", $contents);
if($count>0){
file_put_contents($filename,$contents);
}
However I cant figure out the regex I need to do this, can anyone help? I'm able to select the whole string using this but not the link I need.
"\&[l][t]\;(.*?)\&[g][t]\;"
You can do that without any regex using trim and htmlspecialchars_decode:
$s = '<http://www.test.com>';
$s = trim(htmlspecialchars_decode($s), "<>");
echo $s; // => http://www.test.com
See IDEONE demo
The htmlspecialchars_decode will convert the special HTML entities back to characters, and trim will remove < and > from the start and end of the string.
This was my solution below thanks to Wiktors advice. Hopefully it can help someone else out!
function removeUnwantedSignsFromContact($path){
$contents = file_get_contents($path);
if(preg_match( '/\&[l][t]\;(.*?)\&[g][t]\;/', $contents, $match )){
$filteredContact = trim(htmlspecialchars_decode($match[0]), "<>");
$contents = str_replace($match[0], $filteredContact, $contents);
file_put_contents($path,$contents);
return simplexml_load_file($path);
}
}

PHP: regex to replace a#3 in string

I want to make links using shortcuts following the pattern: controller/#/id. For example: a#3 must be rewritten to /actions/view/3, and t#28 must be a link to /tasks/view/28. I think preg_replace is an "easy" way to achieve this, but I'm not that good with regular expressions and I don't know how to "reuse" the digits from the search-string within the result. I think I need something like this:
$search = array('/a#\d/', '/t#\d/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);
Can someone point me in the right direction?
You can "reuse" the numbers from the search strings using capturing groups, denoted by brackets ().
Try this -
$text = "a#2 a#3 a#5 a#2 t#34 t#34 t#33 t#36";
$search = array('/\ba#(\d+)\b/', '/\bt#(\d+)\b/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);
var_dump($text);
/**
OUTPUT-
string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
**/
The above answer works, but if you need to add more of those search values, you can store those keys in separate array and you can use preg_replace_callback.This also does the same thing, but now, you only need to add more (alphabets)keys in the array and it will replace it accordingly. Try something like this-
$arr = Array(
"a"=> "/actions/view/",
"t"=> "/tasks/view/"
);
$text = preg_replace_callback("/\b([a-z]+)#(\d+)\b/", function($matches) use($arr){
var_dump($matches);
return $arr[$matches[1]].$matches[2];
},$text);
var_dump($text);
/**
OUTPUT-
string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
**/
Since the number is not replaced you can use strtr (if it is not too ambigous) :
$trans = array('a#' => '/actions/view/', 't#' => '/tasks/view/');
$text = strtr($text, $trans);
if you can use this, it will be faster than processing a string two times with a regex.

PHP - strip URL to get tag name

I need to strip a URL using PHP to add a class to a link if it matches.
The URL would look like this:
http://domain.com/tag/tagname/
How can I strip the URL so I'm only left with "tagname"?
So basically it takes out the final "/" and the start "http://domain.com/tag/"
For your URL
http://domain.com/tag/tagname/
The PHP function to get "tagname" is called basename():
echo basename('http://domain.com/tag/tagname/'); # tagname
combine some substring and some position finding after you take the last character off the string. use substr and pass in the index of the last '/' in your URL, assuming you remove the trailing '/' first.
As an alternative to the substring based answers, you could also use a regular expression, using preg_split to split the string:
<?php
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
?>
(The reason for the -2 is because due to the ending /, the final element of the array will be a blank entry.)
And as an alternate to that, you could also use preg_match_all:
<?php
$ptn = "/[a-z]+/";
$str = "http://domain.com/tag/tagname/";
preg_match_all($ptn, $str, $matches);
$tagname = $matches[count($matches)-1];
echo($tagname);
?>
Many thanks to all, this code works for me:
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);

Categories