How can I replace a string from a particular string? Please see my example below.
$string_value="<b>Man one</b> <img src=\"http://www.abc.com/image1.jpg\">and <b>Man two</b> <img src=\"http://www.abc.com/img2.png\">";
Now my expected out put is = <b>Man one</b> and <b>man two</b>. only the image tag should be deleted.
So I have to cut the full string from "<img" to ">" from string $string_value.
So how can I cut the full string between "<img" to ">" using preg_replace or anything else.
The replacing parameter should be blank space.
Looks like you want to strip the tags. You can do it easily by calling the function strip_tags which gets HTML and PHP tags stripped from a given string.
$string_value = strip_tags($string_value);
EDIT:
Since you want to strip only the <img tag, you can make use of this function:
function strip_only($str, $tags) {
if(!is_array($tags)) {
$tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
if(end($tags) == '') array_pop($tags);
}
foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
return $str;
}
and call it as:
$string_value = strip_only($string_value,'img');
Working link
You can use regular expressions to exclude IMG tags:
<?php
$text = "Man one <img src=\"http://www.abc.com/image1.jpg\">and Man two <img src=\"http://www.abc.com/img2.png\">";
$pattern = "/<img(.*?)>/i";
$replace = '';
print preg_replace($pattern,$replace,$text);
?>
Just use strip_tags($string_value); and you will get your desired output.
Related
I'm using PHP to filter my title to remove the word "Tag:" inside and it is working fine, however when my following word starts with "T" it will instantly be removed as well.
This was how i've set my code
<?php $tag = "Tag: ";
if( str_replace( $tag, "", $title) == true ):
else:echo ltrim($title, $tag);
endif ?>
so when my title is Tag: Home it will return Home just fine,
but if my title is something like Tag: Teachers it will return me eachers instead.
How do i make it so I can still display any title starting with T without it being removed.
Try this. it will returns only Teacher
$str = "Tag: Teacher";
$str = str_replace("Tag:", "", $str);
echo $str;
Use following to remove the tag Tag:
<?php
$title = 'Tag: Teachers';
echo removeTag($title); // Teachers
function removeTag(string $str, string $tag = "Tag: "): string
{
$str = str_replace($tag, "", $str);
return $str;
}
For Example
$string = '<i>Line1</i><i><i><i><i><i></i></i></i></i></i><i><i><i><i>
<i>Line 2</i></i></i></i></i><i><i><i><i><i></i></i></i></i>
</i><i><i><i><i><i>Line 3</i></i></i></i></i>';
How do I remove the tag if the content inside of it is Empty and how do I close the tag if it's not closed
using php
< / i >
Please help to solve this problem.
You can use strip_tags for this
$string ='<i>Line1</i><i><i><i><i><i></i></i></i></i></i><i><i><i><i>
<i>Line 2</i></i></i></i></i><i><i><i><i><i></i></i></i></i>
</i><i><i><i><i><i>Line 3</i></i></i></i></i>';
To strip the tags
echo strip_tags($string);
One way through for formatting tags that are not closed is
$doc = new DOMDocument();
$doc->loadHTML($string);
$string = $doc->saveHTML();
We can also use regex to remove empty html tags. Here's a small function to do it.
function remove_empty_tags ($string, $rep = NULL)
{
if (!is_string ($string)
|| trim ($string) == '')
return $string;
return preg_replace ('/<([^<\/>]*)>([\s]*?|(?R))<\/\1>/imsU',!is_string ($rep) ? '' : $rep,$string);
}
$string = remove_empty_tags($string);
I need a regex to strip outer/top level HTML tags in a string but keep the internal ones.
$str = "<div>Start <br /> <span>test</span> end.</div>";
Into
$str = "Start <br /> <span>test</span> end.";
As well as
$str = "<aside id="main" class="one">Start <br /> <span>test</span> end.</aside>";
Into
$str = "Start <br /> <span>test</span> end.";
.
preg_replace('/<[^>]*>/', '', $str);
Removes all tags not just outer ones.
Please note
Using a regex is not the best way to modify HTML code!
In most situations it is better and much more reliable to use a DOMDocument or DOMDocumentFragement object to modify or extract data from HTML code.
However, there are valid scenarios where a regex is better, mainly when these factors apply:
You know that the HTML code that you edit is going to be valid.
The HTML structure that is modified will be identical in all cases.
You're doing only very simple changes to the code.
Performance is important (e.g. when it is executed inside a loop). DOMDocument is considerably slower than a simple regex!
The code
To strip the outermost tag from some HTML code use this regex:
/* Note:
* The code must start with an opening tag and end with a closing tag.
* No white space or other text must be present before the first
* tag/after the last tag, else you get some unexpected results.
*/
$contents = preg_replace( '/^<[^>]+>|<\/[^>]+>$/', '', $markup );
// ^<[^>]+> This removes the first tag
// <\/[^>]+>$ This removes the last closing tag
Examples
This regex works for most HTML markup e.g.
In: '<div class="my-text" id="text" style="color:red">some text</div>'
Out: 'some text' (expected result)
When the first tag contains the ">" character it's going to break everything, e.g.
In: '<div title="Home > Archives">Archive overview</div>'
Out: ' Archives">Archive overview' (unexpected result)
Also whitespace/text in the start or end will break the regex
In: '<div>Your name</div>:'
Out: 'Your name</div>:' (unexpected result)
And of course, any tag will be stripped, without any sanity check, e.g.
In: '<h2>Settings</h2><label>Page Title</label>'
Out: 'Settings</h2><label>Page Title' (unexpected result)
How to take a DOM element, and simulate innerHTML()
$html = '<html><body><div><ul><li>1</li><li>2</li><li>3</li></ul></div></body></html>';
function DOMinnerHTML(DOMNode $element) {
$innerHTML = "";
foreach ($element->childNodes as $child) {
$innerHTML .= $element->ownerDocument->saveHTML($child);
}
return $innerHTML;
}
$doc = new DOMDocument();
$doc->loadHTML($html);
foreach ($doc->getElementsByTagName('ul') as $child) {
$html = DOMinnerHTML($child);
echo $html, PHP_EOL;
}
without having to resort to regexp
This basic regex will probably do. It does not, however, account for tags that have attributes that contain >s, and thus will trip.
Find: <[^>]*>([\s\S]*)<\/[^>]*>
Replace: $1
It gets more complex if you expect attributes may contain tag brackets.
Find: <(?:[^>]*?(?:(?:"[^"]*?"|'[^']*?')+[^>]*?)|[\s\S]*?)>([\s\S]*)<\/[^>]*>
Replace: $1
Either one should do the trick.
I made a function that removes the HTML tags along with their contents:
Function:
<?php
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE) {
return preg_replace('#<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>#si', '', $text);
}
else {
return preg_replace('#<('. implode('|', $tags) .')\b.*?>.*?</\1>#si', '', $text);
}
}
elseif($invert == FALSE) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
return $text;
}
?>
Sample text:
$text = 'sample text with tags';
Result for strip_tags($text):
sample text with tags
Result for strip_tags_content($text):
text with
Result for strip_tags_content($text, ''):
sample text with
Result for strip_tags_content($text, '', TRUE);
text with tags
I hope that someone is useful :)
Say you have a string like
$str = "<img src='i12'><img src='i105'><img src='i12'><img src='i24'><img src='i15'>....";
is it possible to replace every i+n by the nth value of an array called $arr
so that for example <img src='i12'> is replaced by <img src='$arr[12]'>.
If I were you, I'd simply parse the markup, and process/alter it accordingly:
$dom = new DOMDocument;
$dom->loadHTML($str);//parse your markup string
$imgs = $dom->getElementsByTagName('img');//get all images
$cleanStr = '';//the result string
foreach($imgs as $img)
{
$img->setAttribute(
'src',
//get value of src, chop of first char (i)
//use that as index, optionally cast to int
$array[substr($img->getAttribute('src'), 1)]
);
$cleanStr .= $dom->saveXML($img);//get string representation of node
}
echo $cleanStr;//echoes new markup
working demo here
Now in the demo, you'll see the src attributes are replaced with a string like $array[n], the code above will replace the values with the value of an array...
I would use preg_replace for this:
$pattern="/(src=)'\w(\d+)'/";
$replacement = '${1}\'\$arr[$2]\'';
preg_replace($pattern, $replacement, $str);
$pattern="/(src=)'\w(\d+)'/";
It matches blocks of text like src='letter + digits'.
This catches the src= and digit blocks to be able to print them back.
$replacement = '${1}\'\$arr[$2]\'';
This makes the replacement itself.
Test
php > $str = "<img src='i12'><img src='i105'><img src='i12'><img src='i24'><img src='i15'>....";
php > $pattern="/(src=)'\w(\d+)'/";
php > $replacement = '${1}\'\$arr[$2]\'';
php > echo preg_replace($pattern, $replacement, $str);
<img src='$arr[12]'><img src='$arr[105]'><img src='$arr[12]'><img src='$arr[24]'><img src='$arr[15]'>....
Say I have the following text
..(content).............
<A HREF="http://foo.com/content" >blah blah blah </A>
...(continue content)...
I want to delete the link and I want to delete the tag (while keeping the text in between). How do I do this with a regular expression (since the URLs will all be different)
Much thanks
This will remove all tags:
preg_replace("/<.*?>/", "", $string);
This will remove just the <a> tags:
preg_replace("/<\\/?a(\\s+.*?>|>)/", "", $string);
Avoid regular expressions whenever you can, especially when processing xml. In this case you can use strip_tags() or simplexml, depending on your string.
<?php
//example to extract the innerText from all anchors in a string
include('simple_html_dom.php');
$html = str_get_html('<A HREF="http://foo.com/content" >blah blah blah </A><A HREF="http://foo.com/content" >blah blah blah </A>');
//print the text of each anchor
foreach($html->find('a') as $e) {
echo $e->innerText;
}
?>
See PHP Simple DOM Parser.
Not pretty but does the job:
$data = str_replace('</a>', '', $data);
$data = preg_replace('/<a[^>]+href[^>]+>/', '', $data);
strip_tags() can also be used.
Please see examples here.
$pattern = '/href="([^"]*)"/';
I use this to replace the anchors with a text string...
function replaceAnchorsWithText($data) {
$regex = '/(<a\s*'; // Start of anchor tag
$regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
$regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
$regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
$regex .= '(?P<name>\S+)'; // Grab the name
$regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)
if (is_array($data)) {
// This is what will replace the link (modify to you liking)
$data = "{$data['name']}({$data['link']})";
}
return preg_replace_callback($regex, array('self', 'replaceAnchorsWithText'), $data);
}
use str_replace