Add <br> when echo - php

Variable $name (string) gives something like (5 possible values):
"Elton John"
"Barak Obama"
"George Bush"
"Julia"
"Marry III Great"
Want to add <br /> after the first whitespace (" " between words).
So, it should give when echo:
"Elton<br/>John"
"Barak<br/>Obama"
"George<br/>Bush"
"Julia"
"Marry<br/>III Great"
1) <br /> should be added only if there is more than one word in a string.
2) Only after the first word.
3) Can be more than 3 words in variable.

$name = preg_replace('/([^ ]+) ([^ ]+)/', '\1 <br />\2', $name, 1);
Testing it out...
$names=array(" joe ",
"big billy bob",
" martha stewart ",
"pete ",
" jim",
"hi mom");
foreach ($names as $n)
echo "\n". preg_replace('/([^ ]+) ([^ ]+)/', '\1 <br />\2', $n, 1);
..gives...
joe
big <br />billy bob
martha <br />stewart
pete
jim
hi <br />mom

if (($pos = strpos($name, " ")) !== false) {
$name = substr($name, 0, $pos + 1) . "<br />" . substr($name, $pos +1);
}

This implements all your requirements:
$tmp = explode(' ', trim($name));
if (count($tmp) > 1)
$tmp[0] = $tmp[0] . '<br />';
$name = trim(implode($tmp, ' '));

if (count(explode(' ', trim($string))) > 1) {
str_replace(' ', ' <br />', $string);
}

Related

How can I put '-' between words in this code php?

Below code will echo like this
('nice apple'),(' nice yellow banana'),(' good berry ')
what I need to do is that I need them to be like this
('nice-apple'),(' nice-yellow-banana'),(' good-berry ')
The challenge is that I could not touch $str, and then I need to use '-' to connect words if there is space between them, If use str_replace space, it will be something like ----nice-apple-. how can I achieve something like this ('nice-apple'), appreciate.
<?php
$str="nice apple,
nice yellow banana,
good berry
 ";
echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
?>
Try str_replace
$str="nice apple,
nice yellow banana,
good berry
";
$str = array_map(function($dr){ return preg_replace('/\s+/', '-', trim($dr));},explode(',',$str));
$str = implode(',',$str);
echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
Output:
('nice-apple'),('nice-yellow-banana'),('good-berry')
Its bit tricky. Try with -
$str="('nice apple'),(' nice yellow banana'),(' good berry ')";
$v = explode(',', $str); // generate an array by exploding the string by `,`
foreach($v as $key => $val) {
$temp = trim(str_replace(["(", "'", ")"], "", $val)); //remove the brackets and trim the string
$v[$key] = "('".str_replace(" ", "-", $temp)."')"; // place the `-`s
}
$new = implode(",", $v); // implode them again
var_dump($new);
you need to get rid of the new lines first then it'll work.
<?php
$str="nice apple,
nice yellow banana,
good berry
";
$arr = explode(',', str_replace([ "\r\n", "\n" ], "", $str));
$arrCount = sizeOf($arr);
for($x = 0; $x < $arrCount; $x++) {
while (preg_match('/(\w)\s(\w)/', $arr[$x])) {
$arr[$x] = preg_replace('/(\w)\s(\w)/', '$1-$2', $arr[$x]);
}
}
echo $str = "('" . implode("'),('", $arr) . "')";
?>
('nice-apple'),(' nice-yellow-banana'),(' good-berry ')

remove word from string by position from input

EXAMPLE:
input = 2
text = aa bb cc
Will become: aa cc
The input for position is $_POST['position']
i have
$words = explode(" ", $_POST['string']);
for ($i=0; $i<count($words); $i++){
echo $words[$i] . " ";
}
$to_remove = 2;
$text = "aa bb cc";
$words = explode(' ', $text);
if(isset($words[$to_remove -1])) unset($words[$to_remove -1]);
$text = implode(' ', $words);
Pulling out the big guns REGEX !!!
$string = 'aa bb cc dd';
$input = 2;
$regex = $input - 1;
echo preg_replace('#^((?:\S+\s+){'.$regex.'})(\S+\s*)#', '$1', $string);
Output: aa cc dd
Foreach loops tend to make it a little easier to understand (IMO). Looks cleaner too.
$pos = 2;
$sentence = explode(" ", $_POST['string']);
foreach ($sentence as $index => $word) {
if ($index != $pos - 1) {
$result .= $word . ' ';
}
}
echo $result;
This sounds like a homework question. I'll take a stab at it though:
Code:
<?php
$string = trim($_POST['string']);
$parts = explode(" ", string);
$newString = "";
$position = intval($_POST['position']);
for($a = 0; $a < count($parts); $a++) {
if($a != $position) { // or $a != ($position - 1) depending on if you passed in zero based position
$newString = $newString . $parts[$a] . " ";
}
}
$newString = trim($newString);
echo "Old String: " . $string . "<br />";
echo "New String: " . $newString;
?>
Output:
Old String: aa bb cc
New String: aa cc
$input = 2;
$words = explode(" ", $_POST['string']);
unset($words[$input-1]);
$words = implode(" ", $words);
echo $words;

Non alphanumeric characters replaced with a single space

Here's the thing I'm trying to get a search engine to pick up names entered as Doe J instead of Doe, J.
Here is my code:
$sql_where = array();
if (isset($_GET['name'])) {
echo "Searched: {$_GET['name']}<br>";
$names = explode(' ', trim(preg_replace('/ +/', ' ', $_GET['name'])));
$names_cnt = count($names);
if (2 == $names_cnt) {
foreach ($names as $name_idx => $name) {
if (($name_idx+1) == $names_cnt) {
// last one
$sql_where[] = "
(full_name like '% {$name}%')
";
} else {
// first one
$sql_where[] = "
(full_name like '{$name}%')
";
}
}
} else {
$sql_where[] = "
(full_name like '" . $DB->cleanString($_GET['name']) . "%')
";
I've tried /[^a-zA-Z0-9 ]/ and a few other variations that have been unsuccessful.
echo preg_replace( "`[^a-zA-Z0-9]+`", " ", $string);
//replaces all non alpha numeric characters as " "
//(and will not have duplicate spaces)
DEMO: http://codepad.org/7Ltx3kcr

won't remove spaces in string

I'm taking input from textarea form and put it in the long line.
Input is like this:
Country: France
City: Paris
Street: Champ
Then put it in the long line:
$line = $_POST['input'];
now, I need to replace spaces and new lines with <SP> and <BR>, so I do this:
$line = str_replace(" ","&ltSP&gt",$line);
$line = str_replace("\n","&ltBR&gt",$line);
but I get this:
Country:<SP>France <BR> <BR>City:<SP>Paris <BR> <BR>Street:<SP>Champ
Now, if insted of \n I tried this:
$line = str_replace("\r","&ltBR&gt",$line);
I get similar result. If I do them both i Get similar results which obviously has some spaces in it. So Then I do this:
$line = str_replace(" ","",$line);
but it stays the same.
My whole code is:
$line = str_replace(" ","&ltSP&gt",$line);
$line = str_replace("\n","&ltBR&gt",$line);
$line = str_replace(" ","",$line);
echo $line;
How to remove spaces in this case?
Edit:
I did bin2hex and found out that the space is actually carriage return \r.
So this is the solution:
$line = str_replace("\r","",$line);
Why did \r behave like space in this case?
the comments will probably suffice but I thought I'd share this snippet, which given your example I had a punt at what you are trying to achieve.
<?php
// example string data
$str = "key1 value1 key2 value2 key3 value3";
// clean string
$str = str_replace("&nbsp", " ",$str);
$str = str_replace("\n", " ", $str);
$str = str_replace("\r", " ", $str);
$arr = explode(" ", $str);
$out = "<ul>";
$cnt = 1;
foreach($arr as &$val) {
if ($cnt++ % 2 == 0) {
continue;
} else {
$out = $out . "<li>" . $val . ": " . current($arr) . "</li>";
}
}
$out = $out . "</ul>";
echo $out;
// output source
// <ul><li>key1: value1</li><li>key2: value2</li><li>key3: value3</li></ul>
?>

Printing a summary entered by user in textearea in PHP

i have a form textearea field where a user enter a summary like:
il est poli comej hhh kkbkbkbkb
jbbbjbjblb ljlllbbblblb bnlbggkgkgkjg
lkjhhlhlhlhlhlh fin.
I would like to output this in two lines ending with '...' without printing all like
il est poli
comej hhh
kkbbkbkb jbbbjblb...
How to handle this in php ?
<?php
$summary = explode($textarea,' '); //split user input in words
echo $summary [0], ' ',$summary [1], ' ',$summary [2]; //print first 3 words
echo '<br>'; //newline
echo $summary [3], ' ',$summary [4]; //print 2 more words
echo '<br>'; //newline
echo $summary [5], ' ',$summary [6]; //print 2 more words
echo '...'; //dots
?>
This can be:
<?php
$summary = explode($textarea,' '); //split user input in words
echo $summary [0], ' ',$summary [1], ' ',$summary [2],'<br>',$summary [3], ' ',$summary [4],'<br>', $summary [5], ' ',$summary [6],'...';
?>
$str = 'asdf asdf sadf asdf asf asdf asdf asdf sfd';
$cut_length = 100;
if (strlen($str) > $cut_length)
$str = substr($str, 0, $cut_length) .'...';
$line_length = 50;
$str_words = explpode(' ', $str);
$len = 0;
$str = '';
foreach ($str_words as $word) {
$str .= $word . ' ';
$len += strlen($word);
if ($len >= $line_length) {
$str .= '<br/>';
$len = 0;
}
}

Categories