Asked  7 Months ago    Answers:  5   Viewed   48 times

I want to extract the first word of a variable from a string. For example, take this input:

<?php $myvalue = 'Test me more'; ?>

The resultant output should be Test, which is the first word of the input. How can I do this?

 Answers

20

You can use the explode function as follows:

$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
Wednesday, March 31, 2021
 
GGio
answered 7 Months ago
85
substr("testers", -1); // returns "s"

Or, for multibytes strings :

substr("multibyte string…", -1); // returns "…"
Wednesday, March 31, 2021
 
Nil
answered 7 Months ago
Nil
33

Ok, you're going to need more than just PHP to get this done; you'll need JavaScript as well.

Let's start with your HTML. I'm assuming your rendered output looks like the following and I won't question why you're doing it this way.

<div id="dropdown">
    <span>Option One</span>
    <span>Option Two</span>
    <span>Option Three</span>
</div>

So there's my guess at your HTML.

To post a value back to PHP, you're also going to need a way to capture the selected value in an input field that can be posted with a form. A hidden input will probably be the best option for you.

<input type="hidden" name="dropdown-selection" id="dropdown-selection" />

So that's our markup done. Next you'll need to grab the selected option from your div and stick it into the hidden field. I'm assuming you've coded something to render your div to look and behave exactly like a dropdown (ok, I'll bite. Why ARE you doing it this way?).

This is the JavaScript code using jQuery (we only use jQuery on StackOverflow. Just kidding; that's not true. Well, maybe it's a little bit true)

<script type="text/javascript">
    $(function () {
        $('#dropdown-selection').val($('#dropdown span:visible').text());
    });
</script>

Now, as long as you've ensured that the hidden field is contained within a form that posts back to your target PHP page, you'll have the value of the span tag available to you.

I've made quite a few assumptions about how you've gone about setting up your page here. Correct me on any parts that don't tie into reality.

Friday, May 28, 2021
 
Arman
answered 5 Months ago
69
$str = 'In My Cart : 11 12 items';
preg_match_all('!d+!', $str, $matches);
print_r($matches);
Tuesday, June 1, 2021
 
Sanguine
answered 5 Months ago
59

You can do:

preg_split('/.|?|!/',$mystring);

or (simpler):

preg_split('/[.?!]/',$mystring);
Friday, June 25, 2021
 
Tak
answered 4 Months ago
Tak
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :