separate each words in php - php

I had an value in database like "demo text" . I want to display this content from the db in the view page as
Html code that i am using is like this <h2>Demo<span>Text</span></h2> , is there any solution for seperate each words and use one for h2 and other for span. I am using php codeigniter for the project , I don't know that whether the way i explained my problem is correct or not .

Yes you can so it with explode
if you have stored at least 2 words with space. try following
$demo ="demo text";
$arr = explode(" ",$demo);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;
DEMO
EDIT
If you have more words and want to split first word only you can pass limit parameter in explode
$demo ="Pligrimage to Marian Shrines";
$arr = explode(" ",$demo,2);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;
DEMO

I think you are looking for something like this!
$your_string = "Hello Houston! We have a problem!";
$my_array = explode(" ",trim($your_string));
$output = "<h2>";
foreach($my_array as $a_word){
if ($a_word === reset($my_array))
$output .= $a_word;
else
$output .= " <span>". $a_word . "</span>";
}
$output .= "</h2>";
print $output;

Related

PHP find multiple words in string and wrap in <span> tags

Im finding keyword "paintball" in a string, and wrapping it in span tags to change it colour to red like this...
$newoutput = str_replace("Paintball", "<span style=\"color:red;\">Paintball</span>", $output);
echo $newoutput;
Which works, but people are writing it in the field as "Paintball", "paintball", "Paint Ball", "paint ball" etc.
Is there a better way of doing this rather than repeating it for every word?
Ideally something like...
$words = "Paintball", "paintball", "Paint Ball", "paint ball";
$newoutput = str_replace("($words)", "<span>$1</span>", $output);
But im not sure how to write it.
Ok, so a mixture of answers got me here...
$newoutput = preg_replace("/(paint\s*ball|airsoft|laser\s*tag)/i", "<span>$1</span>", $output);
echo $newoutput;
And it works perfectly, thank you very much!
This should work for you:
(Here I just use preg_replace() with the modifier i for case insensitivity)
<?php
$output = "LaSer Tag";
$newoutput = preg_replace("/(Airsoft|Paintball|laser tag)/i", "<span style=\"color:red;\">$1</span>", $output);
echo $newoutput;
?>
EDIT:
Besides that this is invalid syntax:
$words = "Paintball", "paintball", "Paint Ball", "paint ball";
and you probably meant this:
$words = ["Paintball", "paintball", "Paint Ball", "paint ball"];
//^ See here array syntax ^
You can use something like this then
$newoutput = preg_replace("/(" . implode("|", $words) . ")/i", "<span style=\"color:red;\">$1</span>", $output);
You could use preg_replace, passing it an array of words and doing a case-insensitive match using the i modifier:
$patterns = array('/paint\s?ball/i', '/airsoft/i', '/laser tag/i');
$newoutput = preg_replace($patterns, '<span style="color:red;">$0</span>', $string);
The \s? in /paint\s?ball/ matches zero or one spaces - you could use \s* to match zero or more instead if you preferred.
Simple and easy to use
$title = get_the_title($post->ID);
$arraytitle = explode(" ", $title);
for($i=0;$i<sizeof($arraytitle);$i++){
if($i == 0){
echo $arraytitle[0].' ';
}elseif($i >= 0){
echo '<span>'.$arraytitle[$i].'</span>'." ";
}
}
use this:
function colorMyWord($word, $output)
{
$target_words = array('paintball', 'paint ball', 'airsoft');
if(in_array($target_words, $word))
{
$newoutput = str_ireplace($word, "<span style=\"color:red;\">$word</span>", $output);
return $newoutput;
}
Usage :
echo colorMyWord('Paintball', 'I need a Paintball');

How to remove whitespaces from the beginning and end of loop phrase

i need to remove whitespaces from the beginning and end of loop phrase
All words come from an loop, and look like this: " Hello all people "
I'm using the code -
$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
foreach ($appliedFilters as $item) {
if ($item->getFilter()->getRequestVar() == 'b_car' || 'c_model' || 'd_year') {
$n_str = string.replace("\"", "", $item->getLabel()));
echo $n_str;
}
}
This code returns "Helloallpeople"
But i need "Hello all people"
Please help!
UPDATED
var_dump($item->getLabel()); returns string(7) "Hello " string(8) "all " string(5) "People "
Try Regx like the following:
$returnValue = preg_replace("/>\s+(.*)\s+</", '>$1<', '<a> Hello all people <a/>');
I am keeping the old answer for reference.
But if you simply want to remove leading and trailing spaces; use trim()
Update:
If you want to trim each and every element of an array; you can map trim function to it.
Then you can also implode the array to a string.
<?php
$str = array(" Hello all ", " Hello all people ", " all people ", " Hello people ");
$n_str = array_map("trim",$str);
var_dump($n_str);
echo implode(" ",$n_str);
?>
Update 2:
Ok I got it; It's not an array. It's a loop.
Every time $item->getLabel() returns just a string. it's not an array.
Following should help you.
$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
$result = "";
foreach ($appliedFilters as $item) {
if ($item->getFilter()->getRequestVar() == 'b_car' || 'c_model' || 'd_year') {
$result .= " ".trim($item->getLabel());
}
}
echo trim($result);
Try this:
$words = $item->getLabel(); //array(" Hello", "all ", "people ");
echo trim(preg_replace("/\s+/", " ", implode($words, " ")));
// Output: Hello all people
See demo

How to colorize text betwen " * " tags in message?

Anybody knows how i can achieve this:
I want post message and colorize everything between " * " Tags.
Like this:
This [*]is[*] test [*]message[*] :)
To:
This [yellow]is[/yellow]> test [yellow]message[/yellow] :)
I wroted something like this to achieve my goal:
if(preg_match_all('/\*(.*?)\*/',$message,$match)) {
$beforemessage = explode("*", $message, 2);
$message = $beforemessage[0]. " <font color='yellow'>" .$match[0][0]. "</font>";
}
Howewer it returns only:
This [yellow]is[yellow]
Just use preg_replace():
$message = "This *is* test *message*";
echo preg_replace('/\*(.*?)\*/', '<font color="yellow">$1</font>', $message);
This <font color="yellow">is</font> test <font color="yellow">message</font>
preg_match_all returns an array of matches, but your code only ever replaces the FIRST match in that array. You'd have to loop over the array to handle the OTHER matches.
There are a few approaches when using regular expressions.
One is to do matching - keeping track of the position of the match and the length of the match. Then you can split up the original message into substrings and concatenate it all back together.
The other is to do search/replace using regular expressions.
Try this, or similar approach:
<?php
$text = "Hello hello *bold* foo foo *fat* foo boo *think* end.";
$tagOpen = false;
function replaceAsterisk($matches) {
global $tagOpen;
$repl = "";
if($tagOpen) {
$repl = "</b>";
} else {
$repl = "<b>";
}
$tagOpen = !$tagOpen;
return $repl;
}
$result = preg_replace_callback( "/[*]/", "replaceAsterisk", $text);
echo $result;

How can i insert text into html tag in php string?

i have been dealing with this for awhile and i could not figure out how to do the following in PHP:
$string = "this is test <pre>somrthing in <p>pharagraph</p></pre> dont know tell me <pre>value33 kooo ok</pre> this is php regress <pre>teeth value</pre> ok how";
function get_innercode($string) {
preg_match_all("#<pre>(.*?)</pre>#", $string, $foo);
echo implode("\n", $foo[1]);
}
$insert1=get_innercode($string);
$insert2=" 2 place me in the pre tag"; // you can ignore this
$string="this is test <pre> WHERE $insert1 SHOULD BE</pre> dont know tell me <pre>WHERE $insert2 SHOULD BE</pre> ok how ";
how can i do this?
Please note i cannot do
$string="some text here <pre> WHERE $insert1 SHOULD BE</pre> some more text here <pre>WHERE $insert2 SHOULD BE</pre> ok how";
because i am getting $insert1 and $insert2 from $string to modify. i need to place it back in there where they come from.
thank you
It's pretty easy to do:
$insert1 =" 1 place me in the pre tag";
$insert2 =" 2 place me in the pre tag";
$string = "some text here <pre>{$insert1}</pre> some more text here <pre>{$insert2}</pre> and may be some more text or ";
You can echo a variable from inside a string when it's wrapped around double quotes. This does not work with single quotes.
Edit: This might be what you are looking for then:
$string = "This my <code>awesome</code> code";
$string = preg_replace('/<code>(.*?)<\/code>/', '<pre>$1</pre>', $string);
In php you can concatenate strings with a "." before and after, example:
$var1 = "hello";
$var2 = "What's up";
$concat = "Hey, ".$var1." ,".$var2."<br>";
echo $concat;
Similar methodology here. This allows for larger areas to be filled
$insert[0] = "Some Text";
$insert[1] = "Some More Text";
function Parser($content){
$i = 0;
while (preg_match_all('`\<pre\>(.*?)\</pre\>`', $content, $matches)) {
foreach ($matches[0] as $key => $match) {
//$innertext = $matches[1][$key]; //replace with your preferred filler
$innertext = $insert[$i]; //such as this
$replacement = '<pre>' . trim($innertext) . '</pre>';
$content = str_replace($match, $replacement, $content);
$i++;
}
}
}
Parse your line(s) of content like so:
Parser("this is test <pre> WHERE $insert1 SHOULD BE</pre> dont know tell me <pre>WHERE $insert2 SHOULD BE</pre> ok how");
This is untested so may have a couple of bugs in it.
Try this,
I am adding div tag before each pre content. You can also modify content as needed by using $matches[1]
$string_new = preg_replace_callback(
'#<pre>(.*?)</pre>#',
function ($matches) {
return "<div>".$matches[0]."</div>";
},
$string
);
echo $string_new;

PHP: insert text up to delimiter

I have a bunch of chat logs that look like this:
name: some text
name2: more text
name: text
name3: text
I want to highlight the just the names. I wrote some code that should do it, however, I was wondering if there was a much cleaner way than this:
$line= "name: text";
$newtext = explode(":", $line,1);
$newertext = "<font color=red>".$newtext[0]."</font>:";
$complete = $newertext.$newtext[1];
echo $complete;
Looks fine, although you can save the temp variables:
$newtext = explode(":", $line,1);
echo "<font color=red>$newtext[0]</font>:$newtext[1]";
This might be faster or might not, you'd have to test:
echo '<font color=red>' . substr_replace($line, '</font>', strpos($line, ':') , 0);
The answer posted by gview is the simplest it gets, however and just as a reference you can use a regular expression to find the name tag, and replace it with the new html code using preg_replace() as follows:
// Regular expression pattern
$pattern = '/^[a-z0-9]+:?/';
// Array contaning the lines
$str = array('name: some text : Other text and stuff',
'name2: more text : : TEsting',
'name: text testing',
'name3: text Lorem ipsum');
// Looping through the array
foreach($str as $line)
{
// \\0 references the first pattern match which is "name:"
echo preg_replace($pattern, "<font color=red>\\0</font>:", $line);
}
also try the RegExp like this:
$line = "name: text";
$complete = preg_replace('/^(name.*?):/', "<font color=red>$1</font>:", $line);
echo $complete ;
EDIT
if their names aren't "name" or "name1", just delete the name in pattern, like this
$complete = preg_replace('/^(.*?):/', "<font color=red>$1</font>:", $line);

Categories