split <b>'s in php - php

For this code i need to take a string like
<b>hey</b> more text<b>hey2</b> other text
and i expect the returned array to look like
<b>hey</b> more text
<b>hey2</b> other text
However it doesnt. How do i make it look like the above? my test code is
$myArr = split("<b>", "<b>hey</b> more text<b>hey2</b> other text");
foreach($myArr as $e)
{
echo "e = $e\n-------------\n";
}
output is
e =
-------------
e = hey</b> more text
-------------
e = hey2</b> other text
I need the b>'s to remain. How should i remove the first empty array?

echo "e = <b>$e\n-------------\n";
You need to prepend the <b> because split removes it from the string.
As for the empty elements of the array try:
$array = array_filter($array);

the "split" function has been deprecated, it is better not to use it.
Instead, use "explode" on <b> and then prepend back onto each element, and pop the first element off the array.

you could use it as you have it and add a $e = "".$e; before the echo

You can add the <b> after splitting, and just pop() the first variable in the array.

Related

How to add string after specific character in PHP

I am working with php. I have some dynamic string. Now I want to add some number after some string. Like, I have a string this is me (1). Now I want to add -7 after 1. So that string should be print like this this is me (1-7).
I have done this properly by using substr_replace. like this
substr_replace('this is me (1)','-59',-1,-1)
Now if there is more than one number like this this is me(2,3,1). I want to add -7 after each number. like this one this is me(2-7,3-7,1-7).
Please help. TIA
I dont know if there is a good way to do this in one or two lines, but the solution I came up with looks something like this:
$subject = "this is me (2,3,1)";
if (preg_match('[(?<text>.*)\((?<numbers>[0-9,]+)\)]', $subject, $matches)) {
$numbers = explode(",", $matches['numbers']);
$numbers = array_map(function($item) {
return $item.'-7';
}, $numbers);
echo $matches['text'].'('.implode(",", $numbers).')';
}
What happens here is the following:
preg_match checks whether the text is in our desired format
We generate an array from our captured named group numbers with explode
We add our "Magic Value" (-7) to every array element
We're joining the text back together

how to convert letters into array in php

i am trying to convert letters into array.
All the letters are coming from mysql results randomly
for($column=0;$column<8;$column++){
echo '<div class="'.bluexyz.'">'.
$field1 = mysql_fetch_object($sql)->code
.'</div>';
}
each individual letter is a div named bluexyz.
now i want to convert these letters into array.
i have used explode inside the forloop which is not working.
$array = explode('\n',$field1);
it is placing all the letters in the array index of [0]. i want to place a one letter in the one index.
It'd be easier if you provide a clearer explanation and provide an example of what you're fetching and what exactly you're expecting the output to be.
From what I understand, you're trying to convert the $field1 string into array.
You could use str_split() function here.
Try this:
$array = str_split($field1);
echo "<pre>";
print_r($array);
echo "</pre>";
Hope this helps.

php do while loop, display plus sign between results

I would want to display a plus sign between my do while loop result as illustrated below:
If i get two results i would want it to display as e.g. 46+56 and if three results 45+76+89.
Where do i place the plus sign + so that it does not display at the ends?
<?php do { ?>
+ <?php echo $row_studentcat['marks']; ?>
<?php } while ($row_studentcat = mysql_fetch_assoc($studentcat)); ?>
The code above would display result as +45+56 but i would want it to display as 45+56
Any help..
You should use the ltrim() function instead:
echo ltrim($s,'+');
Otherwise, rtrim() will do the same right hand side
For removing + sign from starting (left side), you can use ltrim() function:
Example:
$Yourstring = '+45+10';
echo ltrim($Yourstring,'+'); //45+10
Second param of Function ltrim() will remove the starting + from your string.
From PHP Manual:
ltrim — Strip whitespace (or other characters) from the beginning of a
string
I would implode the data so I can store the data from the other columns in other variables.
$marks = array();
while($row = mysql_fetch_assoc($studentcat)) {
$marks[] = $row['marks'];
}
echo implode('+', $marks);
This is very simple my friend, use php JOIN()...
<?php
$marksArray= array()l
while ($row_studentcat = mysql_fetch_assoc($studentcat))
{
$marksArray[] = $row_studentcat['marks'];
}
echo join('+',$marksArray);
?>
The faster way is concatenating the elements into a string and delete the first + using this method:
substr($string, 1);
Comparing with implode is 3 times faster and comparing with ltrim is a little bit faster because we only change the index array in this case, which is faster than remove an element
Furthermore, I would like to comment you two important issues of this code:
In case mysql_fetch_assoc returns you an empty result you will have an error, because you will try to access to an unexisting index array, better use while(){}
The method mysql_fetch_assoc is deprecated and is removed in PHP7, your code will have problems in the future: http://php.net/manual/es/function.mysql-fetch-assoc.php

How to create array with this in php

I have list in html text arealike this.
12345
23456
12345
78938
85768
my question, how to get the list and create new array with list format..?
sorry about my english
It's unclear what you mean, exactly, but I am assuming you have a list of numbers, separated by line breaks. In that case, you can do this:
explode("\n", $the_string);
If you need to strip out carriage returns (like on Windows), do this:
explode("\n", preg_replace("/\r/", "", $the_string));
jQuery : Get textarea value and replace new line with comma
var txtval = $.trim($("#txtareaid").val()).replace(/\r?\n/g, ',');
// PASS jQuery variable to PHP
PHP: explode() function to convert string into an array based on comma
$a = txtval;
print_r(explode(',', $a));
First You want to Create Array Then,
Use it
$arr1 = array("12345","23456","12345");
echo "I want need".$arr1[0]."";
Say you submit the form to 1.php
code(1.php)
$text=$_REQUEST['t1'];
$arr=explode("\n", trim($text));//$arr is the array of all the entries in the textarea with name 't1'

TextArea to Array with PHP

I'm trying to figure out how to convert html textarea into php array,
I've used a form with POST to deliver the query to the php script,
and the php file is getting them with the following line:
$ids = array($_POST['ids']);
Needless to say that it puts everything into one line
Array ( [0] => line1 line2 line3 line4 )
I need the final results to replace this:
$numbers = array(
"line1",
"line2",
"line3",
"line4"
);
What would be the best approach to divide and re-parse it ?
Using an explode on \n is a proper way to get new lines. keep in mind though that on some platforms the end of line is actually send by \r\n, so just exploding on \n could leave you with extra data on the end of each line.
My suggestion would be to remove the \r before exploding, so you dont have to loop through the entire array to trim the result. As a last improvement, you dont know that there actually is a $_POST['ids'], so always check it first.
<?
$input = isset($_POST['ids'])?$_POST['ids']:"";
//I dont check for empty() incase your app allows a 0 as ID.
if (strlen($input)==0) {
echo 'no input';
exit;
}
$ids = explode("\n", str_replace("\r", "", $input));
?>
I would've done the explode by Hugo like this:
$ids = explode(PHP_EOL, $input);
manual Predefined Constants
Just my two cents...
Use this
$new_array = array_values(array_filter(explode(PHP_EOL, $input)));
explode -> convert textarea to php array (that lines split by new line)
array_filter -> remove empty lines from array
array_values -> reset keys of array
If the textarea simply has line breaks per entry then I'd do something like:
$ids = nl2br($_POST['ids');
$ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses.
Try with explode function:
$ids = $_POST['ids']; // not array($_POST['ids'])
$ids = explode(" ", $ids);
The first parameter is the delimiter which could be space, new line character \r\n, comma, colon etc. according to your string from the textarea (it's not clear from the question whether values are separated by spaces or by new lines).

Categories