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;
Related
I am trying to write some PHP code that will separate words when the are two with "&" and a comma when they are three and the last two with "&"
Something like this
$string = "stack over flow";
Print on screen like this "stack, over & flow";
Hope you noticed the comma and the ampersand.
Then when they are two words
$string = "stack overflow";
print like this echo "stack & overflow";
Here is my code I have been trying, but I am not getting it right:
$string = '1,2';
$list = explode(',',$string);
foreach($list as $row) {
if($list = 2) {
echo ''.$row.' &';
}
}
This should take into account the possibilities of one or more words. If there is more than one word, just remove the last word (using array_pop()) and implode() with , the remaining words.
If there is only 1 word, the result is the same as the original string...
$string = "stack over";
$list = explode(" ", $string);
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = implode(", ", $list) . " & {$last}";
}
else {
$result = $string;
}
To add anchor tags to each word...
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode("</a>, {$aTag}", $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks Nigel Ren.. you code was really helpfully
but their a correction i made.Here
$string = "stack over flow";
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode('</a>, '.$aTag.'', $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks
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 ')
i need to extract and show some words before and after a query word, something like google search results, for example:
$str = "hi user! welcome to new php open source world, we are trying to learn you something!";
$query = "new php";
$result = "... welcome to new php open source ...";
i searched google an SO but didn't find a clear answer or maybe my php knowledge was not enough!
is there a workable and easy-to-use function to do this job?
function yourFuncName($str, $query, $numOfWordToAdd) {
list($before, $after) = explode($query, $str);
$before = rtrim($before);
$after = ltrim($after);
$beforeArray = array_reverse(explode(" ", $before));
$afterArray = explode(" ", $after);
$countBeforeArray = count($beforeArray);
$countAfterArray = count($afterArray);
$beforeString = "";
if($countBeforeArray < $numOfWordToAdd) {
$beforeString = implode(' ', $beforeArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$beforeString = $beforeArray[$i] . ' ' . $beforeString;
}
}
$afterString = "";
if($countAfterArray < $numOfWordToAdd) {
$afterString = implode(' ', $afterArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$afterString = $afterString . $afterArray[$i] . ' ';
}
}
$string = $beforeString . $query . ' ' . $afterString;
return $string;
}
Output is: user! welcome to new php open source world, ($numOfWordToAdd = 3)
Here is an working example I thing that it is clear what I did and how:
<?php
$str = "hi user! welcome to new php open source world, we are trying to learn you something!";
$query = "new php";
$expl = explode($query, $str);
// items on the left side of middle string
$expl_left = explode(" ", $expl[0]);
$left_cnt = count($expl_left);
$new_left = $expl_left[$left_cnt-3] . " " . $expl_left[$left_cnt-2];
// items on the right side of middle string
$expl_right = explode(" ", $expl[1]);
$new_right = $expl_right[1] . " " . $expl_right[2];
// new string formated
$new = "... " . $new_left . " " . $query . " " . $new_right . " ...";
print $new;
?>
If you have some questions feel free to ask...
$result = preg_replace('/(.+)?([^\s]+.{10}'.$query.'.{10}[^\s]+)(.+)?/', '... $2 ...', $str);
This will return the same result from the same string and query you gave. If the before or after length starts or ends (respectively) in the middle of a word, it will continue until it completes the word before it stops.
Assuming a "word" is any series of non-whitespace characters, the following will extract 3 words on either side of new php out of the string $subject, but accept less if necessary:
if (preg_match('/(?:\S+\s+){1,3}new php(?:\s+\S+){1,3}/', $subject, $regs)) {
$result = $regs[0];
}
Change the 3s to any number you like.
I used the following function with explode:
public static function returnSearch($query, $str, $wordcount) {
$explode = explode($query, $str);
$result = null;
//if explode count is one the query was not found
if (count($explode) == 1) {
$result = implode(' ', array_slice(str_word_count($explode[0], 2), -$wordcount, $wordcount)) . " ";
}
//if explode count is more than one the query was found at least one time
if (count($explode) > 1) {
//check for if the string begins with the query
if (!empty($explode[0])) {
$result = "..." . implode(' ', array_slice(str_word_count($explode[0], 2), -$wordcount, $wordcount)) . " ";
}
$result = $result . $query;
if (!empty($explode[1])) {
$result = $result . " " . implode(' ', array_slice(str_word_count($explode[1], 2), 0, $wordcount)) . "...";
}
}
//return result
return $result;
}
Corrected function from #Can Vural, it wont mess the phrase of the before match and its case insensitive, very usefull to dispaly in php search results:
function render_search_words($str, $query, $numOfWordToAdd) {
list($before, $after) = preg_split("/$query/i", $str);
$before = rtrim($before);
$after = ltrim($after);
$beforeArray = explode(" ", $before);
$afterArray = explode(" ", $after);
$countBeforeArray = count($beforeArray);
$countAfterArray = count($afterArray);
$beforeString = "";
if($countBeforeArray < $numOfWordToAdd) {
$beforeString = implode(' ', $beforeArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$beforeString = $beforeArray[$i] . ' ' . $beforeString;
}
}
$afterString = "";
if($countAfterArray < $numOfWordToAdd) {
$afterString = implode(' ', $afterArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$afterString = $afterString . $afterArray[$i] . ' ';
}
}
$string = '...'.$beforeString . ' <span>' . $query . '</span> ' . $afterString.'...';
return $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(" ","<SP>",$line);
$line = str_replace("\n","<BR>",$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","<BR>",$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(" ","<SP>",$line);
$line = str_replace("\n","<BR>",$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(" ", " ",$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>
?>
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;
}
}