Ar Adrian
Ar Adrian

Reputation: 21

Formatting text inside a textarea using php code

I have 2 textareas. In the first textarea the user adds text which i need to modify. In the 2nd textarea the amended text is displayed.

Text that I need to modify has the following format:

23.10.15
Text1
Text2

I want to put text on the same line. Between the 2nd and 3rd line I want "-" to appear, like this:

23.10.15 Text1 - Text2

My code looks like this:

if(isset($_POST["submit"])) {
 $text = $_POST["text-modify"];
 $text = str_replace('', '', $text);
}
    ?>

<form id="form1" name="form1" method="post" action="">

<input type="submit" name="submit" id="submit" value="Submit" />

<textarea name="text-modify" id="text-modify" cols="75" rows="7000">
</textarea>

<textarea name="text-final" id="text-final" cols="75" rows="7000">
<?php echo $text; ?>
</textarea>
</form>

Thank you in advance.

Upvotes: 1

Views: 1444

Answers (2)

dave
dave

Reputation: 64695

Explode the text on newlines, pop off the last item, implode with spaces, append the dash and the last piece:

$pieces = explode("\n", $text);
$last = array_pop($pieces);
$text = implode(" ", $pieces) . " - " . $last;

Even better could be:

$text = call_user_func_array('sprintf', array_merge(["%s %s - %s"], explode("\n", $text)); 

Upvotes: 2

RyanM
RyanM

Reputation: 761

You can put your php in the html to make it simpler like such :

<textarea name="text-modify" id="text-modify" cols="75" rows="7000"><?php $yourVar ?></textarea>

or embed with a string

<textarea name="text-modify" id="text-modify" cols="75" rows="7000"><?php echo "Hi I am ". $nameVar ." How are you ? "</textarea>

Upvotes: 0

Related Questions