$item_content = '<p>'. str_replace('\n\n', '</p><p>', $item_content) .'</p>';
<?php
$item_content = '<img class="attachment-frontpage-smallthumb wp-post-image" width="140" height="80" title="Screen shot 2013-10-25 at 11.55.11 AM" alt="Screen shot 2013-10-25 at 11.55.11 AM" src="http://media.gizmodo.co.uk/wp-content/uploads/2013/10/Screen-shot-2013-10-25-at-11.55.11-AM.png">
How do you revive the Sh*t Girls Say meme that’s dead not only because we all grew tired of it, but because YouTube productivity assassins (aka movie makers) simply ran out of different types of people to make fun of? You reverse it and switch it into shit people would NEVER say. Like nerds thinking [...]
<img width="1" height="1" border="0" src="http://gizmodo.feedsportal.com/c/34920/f/644110/s/32e94f6a/sc/1/mf.gif">
<br clear="all">';
?>
I'm trying to seperate the text so that the text will get wrapped with a <p> tag but the str_replace I've gotten wraps my entire string including image with <p>
What happends if you use:
$p_pos = strpos($item_content, '<p>');
$item_content = substr($item_content, 0, $p_pos) . '<p>'. str_replace('\n', '</p>', str_replace('\n', '<p>', substr($item_content, $p_pos)) .'</p>';
That might solve your problem.
That kind of str_replace will be of no use here. And you should know that your task is not well posed. Some minimal change in HTML markup or even type of space characters (newline or not) will render previously working solution incorrect.
If text content you are willing to wrap is always in a separate line and all other lines starts with tag (like in your current sample), you can try to use logic like this:
function wrapTextLines( $content, $whichTag='p' ) {
$output = '';
foreach( explode("\n",$content) as $line ) {
$line = trim($line);
if( $line[0]!='<' )
$output .= "<{$whichTag}>{$line}</{$whichTag}>\n";
else
$output .= "{$line}\n";
}
return $output;
}
(Here it is in PHPfiddle)
Or another try is this regex, that will transform given HTML code, wrapping every text node (text between tags, containing something besides spaces) into <p> tag.
$wrapped_content = preg_replace(
'#>\s*([^\s<][^<]+)<#ms',
'><p>$1</p><',
$item_content
);
(Here it is in PHPfiddle)
Or, being more specific, will wrap every text node going after <img> tag.
$wrapped_content = preg_replace(
'#(<img[^>]+>)\s*([^\s<][^<]+)<#ims',
'$1<p>$2</p><',
$item_content
);
(Here it is in PHPfiddle)
Related
I would like to cut every text ( image alt included ) in an HTML string form a specific word.
for example this is the string:
<?php
$string = '<div><img src="img.jpg" alt="cut this text form here" />cut this text form here</div>';
?>
and this is what I would like to output
<div>
<a href="#">
<img src="img.jpg" alt="cut this text" />
cut this text
</a>
</div>
The $string is actually an element of an Object but I didn't wanted to put too long code here.
Obviously I can't use explode because that would kill the HTML markup.
And also str_replace or substr is out because the length before or after the word where it needs to be cut is not constant.
So what can I do to achive this?
Ok I solved my problem and I only post an answer to my question because it could help someone.
so this is what I did:
<?php
$string = '<div><img src="img.jpg" alt="cut this text form here" />cut this text form here</div>';
$txt_only = strip_tags($string);
$explode = explode(' from', $txt_only);
$find_txt = array(' from', $explode[1]);
$new_str = str_replace($find_txt, '', $string);
echo $new_str;
?>
This might not be the best solution but it was quick and did not involve DOM Parse.
If anybody wants to try this make sure that your href or src or any ather attribute what needs to be untouched doesn't have any of the chars in the same way and order as in $find_txt else it will replace those too.
This might not even be possible but I have quite a limited knowledge of PHP so I can't figure out if it is or not.
Basically I have a string $myText and this string outputs HTML in the following format:
<p>This is the main bit of text</p>
<small> This is some additional text</small>
My aim is to limit the number of characters displayed specifically within the <p> tag, for example 10 characters.
I have been playing around with PHP substr but I can only get this to work on all of the text, not just the text in the <p> tag.
Do you know if this is possible and if it is, do you know how to do it? Any pointers at all would be appreciated.
Thank you
The simplest solution is:
<?php
$text = '
<p>This is the main bit of text</p>
<small> This is some additional text</small>';
$pos = strpos($text,'<p>');
$pos2 = strpos($text,'</p>');
$text = '<p>' . substr($text,$pos+strlen('<p>'),10).substr($text,$pos2);
echo $text;
but it will work just for first pair of <p> ... </p>
If you need more, you can use regular expressions:
<?php
$text = '
<p>This is the main bit of text</p>
<small> This is some additional text</small>
<p>
werwerwrewre
</p>';
preg_match_all('#<p>(.*)</p>#isU', $text, $matches);
foreach ($matches[1] as $match) {
$text = str_replace('<p>'.$match.'</p>', '<p>'.substr($match,0,10).'</p>', $text);
}
echo $text;
or even
<?php
$text = '
<p>This is the main bit of text</p>
<small> This is some additional text</small>
<p>
werwerwrewre
</p>';
$text = preg_replace_callback('#<p>(.*)</p>#isU', function($matches) {
$matches[1] = '<p>'.substr($matches[1],0,10).'</p>';
return $matches[1];
}, $text);
echo $text;
However in those all 3 cases, all white characters are assumed as part of the string, so if the content of <p>...</p> starts with 3 spaces and you want to display only 3 characters, you simple display only 3 spaces, nothing more. Of course it can be quite easily modified, but I mentioned it to notice that fact.
And one more thing, quite possible you will need to use multibyte version of functions to get the result, so for example instead of strpos() you should use mb_strpos() and set earlier utf-8 encoding using mb_internal_encoding('UTF-8'); to make it working
You can achieve it by a quite simple way:
<?php
$max_length = 5;
$input = "<b>example: </b><div align=left>this is a test</div><div>another very very long item</div>";
$elements_count = preg_match_all("|(<[^>]+>)(.*)(</[^>]+>)|U",
$input,
$out, PREG_PATTERN_ORDER);
for($i=0; $i<$elements_count; $i++){
echo $out[1][$i].substr($out[2][$i], 0, $max_length).$out[3][$i]."\n";
}
these will work for any tag and any class or attribute within it.
ex. input:
<b>example: </b><div align=left>this is a test</div><div>another very very long item</div>
output:
<b>examp</b>
<div align=left>this </div>
<div>anoth</div>
I've found this code already for dealing with content between tags
$content_processed = preg_replace_callback(
'#\<pre\>(.+?)\<\/pre\>#s', create_function(
'$matches',
'return "<pre>".htmlentities($matches[1])."</pre>";' ), $content );
but how could I get it to just get a section of the HTML. The bit I'm looking at starts with;
click here</a></p><p><span class='title'>Soups<br />
and ends at
<div style='font-size:0.8em;'>
(The parts I've chosen are quite long because that way they are unique in the HTML.)
Do not parse html with regex. Bad, bad idea. Better use an XML parser to make it a nested object/array. That way you will be off much safer.
HOWEVER, if you use static code only on your web page (EG code that is never subject to change), you can just explode on that delimiter to chop the page in two halves, and explode again
example:
$html = file_get_contents('path/to/page.phtml');
$text = explode('click here</a></p><p><span class=\'title\'>Soups<br />', $html);
$text = explode('<div style='font-size:0.8em;'>', $text[1]);
$text = $text[0];
echo $text;
So, I have a regex that searches for HTML tags and modifies them slightly. It's working great, but I need to do something special with the last closing HTML tag I find. Not sure of the best way to do this. I'm thinking some sort of reverse reg ex, but haven't found a way to do that. Here's my code so far:
$html = '<div id="test"><p style="hello_world">This is a test.</p></div>';
$pattern = array('/<([A-Z][A-Z0-9]*)(\b[^>]*)>/i');
$replace = array('<tag>');
$html = preg_replace($pattern,$replace,$html);
// Outputs: <tag><tag>This is a test</p></div>
I'd like to replace the last occurance of <tag> with something special, say for example, <end_tag>.
Any ideas?
If I read this right, you want to find the last closing tag in the document.
You could find the last occurrence of </*> which has no more '<>' characters after it. This will be the last tag, assuming all remaining angle-brackets are encoded as < and >:
<?php
$html = '<div id="test"><p style="hello_world">This is a test.</p></div>';
// Outputs:
// '<div id="test"><p style="hello_world">This is a test.</p></tag>'
echo preg_replace('/<\/[A-Z][A-Z0-9]*>([^<>]*)$/i', '</tag>$1', $html);
This will replace the final </div> with </tag>, preserving any content that follows the final closing tag.
I don't know why you'd want to do this with only the closing tag, as if you change it you also have to change the matching opening tag. Also, this will fail to find the last self-closing tag, like <img /> or <br />.
I believe this method works the same as #meager's, but is more concise:
<?php
$html = '<div id="test"><p style="hello_world">This is a test.</p></div>';
$readmore = ' Read More…';
// Outputs:
// '<div id="test"><p style="hello_world">This is a test.</p> Read More…</div>'
echo preg_replace('#</\w>\s*$#', $readmore .'$1', $html);
?>
i want to change the word :)) to a smily img before displaying it from database with php how can i do that
A solution would be to use the str_replace function.
For instance (Using ":-)", which I like more than your ":))" -- only a matter of taste ^^ Up to you to use the "right one") :
$str = "This is a sentence with a smiley :-)";
$new_str = str_replace(
array(
':-)',
),
array(
'<img src="smiley.png" alt=":-)" />'
),
$str
);
echo $new_str;
Will get you this output :
This is a sentence with a smiley <img src="smiley.png" alt=":-)" />
i.e. the smiley has been replaced with an image.
Note that I used an array for the first and second parameter, when calling str_replace : if you have other smileys, you can just add them to those two arrays (the first array being for the "searched" string, and the second for the "replacement").
(What I mean is : no need to call str_replace several time : one time, using arrays, should be enough for several replacements)
And, as a sidenote : I used the original "text" of the smiley for the alt attribute of the img tag : this way, if the image cannot be displayed, the browser will display the textual version of the smiley -- which is better than nothing.
You could use something like:
str_replace(':))', '<img src="path to your image" title="image title" />', $string);
If you want to replace multiple 'smileys', use arrays:
$find = array(
':)',
':('
);
$replace = array(
'<img src="path to happy image" title="" />',
'<img src="path to sad image" title="" />');
);
str_replace($find, $replace, $string);
You can use something like the following. Create a new replacement for each image you've got.
$message = str_replace(":)", "<img src='happy.png' alt=':)'/>", $message);
$message = str_replace(":(", "<img src='unhappy.png' alt=':('/>", $message);
This will turn $message "I'm happy :)" into "I'm happy <img src='happy.png' alt=':)'/>". The alt tag reveals the original smiley when users don't see images.